diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/first-hunk-only.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..66909854345cce32ce30b14b2a7f823194057eb0 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/first-hunk-only.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 4799553204e5b1221dc6b0be9d7ea94c7e3be4f9..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -110,9 +110,7 @@ + + @property + def message(self) -> str: +- if hasattr(self, '_msg'): +- return self._msg +- return "" ++ return self._message + + @property + def exceptions( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qehwklvp/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..cd807d434f3a69ad189c59616bd3bcf1276a8f28 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "c68ac6e7d7b1b38e90c59ce45d47c6a722ce8e9971b65335f1c598bd59a7a8d7", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "369230b94ab16c256349bf5d5b2670133aee18bbcf1d80f52adf8b31b5cd057c", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "715122d022d258ff100be2a0ccf1faa694f1973b4e317b84d9fdd63d98caa8c2", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1", + "source_completion_sha256": "5db6ea55490a17844eb972c9dcce31a84c1ae0933ba8626b570059867468266b", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "c45d1874947b267e4b292561e2648ebe51913ef3e2a68f6901977cb4d52abd2d", + "is_fork": true, + "learner_path": "tasks/fe67ef95fd9d5db546113c55/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "36b6dca9cc55639e2236e8be375369c4a7a6631d6124753dbac800c26e27407d", + "provenance_path": "tasks/fe67ef95fd9d5db546113c55/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "fd596d13e9491292248ca347cb2b2eafb56f9bd7", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "task_sha256": "5e37ded2ca383688e19c649414dc2aa9186db9c8637ee00ced36634e1345e5a1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f541b1adabecb3b9a2b19d57b828c281fe08383e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/instruction.md @@ -0,0 +1,35 @@ +BaseExceptionGroup constructor validation broken after recent changes + +#### Description + +The BaseExceptionGroup constructor is not properly validating input arguments and has broken type checking logic. When creating exception groups with invalid arguments or mixed exception types, the validation either fails completely or produces incorrect error messages. + +#### Steps/Code to Reproduce + +```python +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + +# This should raise TypeError but doesn't validate properly +try: + BaseExceptionGroup(123, [ValueError("test")]) +except Exception as e: + print(f"Got: {e}") + +# This should work but validation logic is broken +try: + ExceptionGroup("test", [ValueError("foo"), KeyboardInterrupt("bar")]) +except Exception as e: + print(f"Got: {e}") + +# Constructor argument validation is inconsistent +try: + BaseExceptionGroup("test", "not a sequence") +except Exception as e: + print(f"Got: {e}") +``` + +The error messages and validation behavior are inconsistent with what's expected. The constructor should properly validate that the message is a string, exceptions parameter is a non-empty sequence, and handle the type hierarchy correctly between BaseExceptionGroup and ExceptionGroup. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..685844f3fd3a43e46d14dc02c95559d15a77f491 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/metadata.json @@ -0,0 +1,237 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_suppress.py::test_suppress_exception" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_async_handler", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "fd596d13e9491292248ca347cb2b2eafb56f9bd7", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch_py311.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_catch.py", + "tests/test_exceptions.py", + "tests/test_formatting.py", + "tests/test_suppress.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_exceptions.py", + "src/exceptiongroup/_formatting.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 324118, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "c45d1874947b267e4b292561e2648ebe51913ef3e2a68f6901977cb4d52abd2d", + "is_fork": true, + "learner_path": "tasks/fe67ef95fd9d5db546113c55/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "36b6dca9cc55639e2236e8be375369c4a7a6631d6124753dbac800c26e27407d", + "provenance_path": "tasks/fe67ef95fd9d5db546113c55/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "fd596d13e9491292248ca347cb2b2eafb56f9bd7", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "task_sha256": "5e37ded2ca383688e19c649414dc2aa9186db9c8637ee00ced36634e1345e5a1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..95f36dd6bd19c8ce5e179d6933481b9380eafb29 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c68ac6e7d7b1b38e90c59ce45d47c6a722ce8e9971b65335f1c598bd59a7a8d7", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "5db6ea55490a17844eb972c9dcce31a84c1ae0933ba8626b570059867468266b", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "8bdda4562087d1c42374a06ae27cf04eb5548aef236de2bd17df953f39c04aef", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "c45d1874947b267e4b292561e2648ebe51913ef3e2a68f6901977cb4d52abd2d", + "is_fork": true, + "learner_path": "tasks/fe67ef95fd9d5db546113c55/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "36b6dca9cc55639e2236e8be375369c4a7a6631d6124753dbac800c26e27407d", + "provenance_path": "tasks/fe67ef95fd9d5db546113c55/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "8f4b9452fb4e2e0e43925a8cb42e6bfb80c368f1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "fd596d13e9491292248ca347cb2b2eafb56f9bd7", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m", + "task_sha256": "5e37ded2ca383688e19c649414dc2aa9186db9c8637ee00ced36634e1345e5a1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..878fc99050ccc8ffc3e0bf5f6b37e726a882dc3f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/provided-gold.diff @@ -0,0 +1,90 @@ +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index e39c9f74e783a6b30a39dd0fb19bc5883e7ff54a..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -56,26 +56,47 @@ + class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): + """A combination of multiple unrelated exceptions.""" + +- def __new__(cls: type[_BaseExceptionGroupSelf], __message: str, +- __exceptions: Sequence[_BaseExceptionT_co]) ->_BaseExceptionGroupSelf: +- """Create a new BaseExceptionGroup instance.""" ++ def __new__( ++ cls: type[_BaseExceptionGroupSelf], ++ __message: str, ++ __exceptions: Sequence[_BaseExceptionT_co], ++ ) -> _BaseExceptionGroupSelf: + if not isinstance(__message, str): +- raise TypeError(f"message must be a string, not {type(__message).__name__}") +- ++ raise TypeError(f"argument 1 must be str, not {type(__message)}") ++ if not isinstance(__exceptions, Sequence): ++ raise TypeError("second argument (exceptions) must be a sequence") + if not __exceptions: +- raise ValueError("exceptions must be a non-empty sequence") +- ++ raise ValueError( ++ "second argument (exceptions) must be a non-empty sequence" ++ ) ++ + for i, exc in enumerate(__exceptions): + if not isinstance(exc, BaseException): +- raise TypeError( +- f"Item {i} of exceptions sequence: expected an exception object, " +- f"got {type(exc).__name__}" ++ raise ValueError( ++ f"Item {i} of second argument (exceptions) is not an exception" + ) +- +- instance = super().__new__(cls) ++ ++ if cls is BaseExceptionGroup: ++ if all(isinstance(exc, Exception) for exc in __exceptions): ++ cls = ExceptionGroup ++ ++ if issubclass(cls, Exception): ++ for exc in __exceptions: ++ if not isinstance(exc, Exception): ++ if cls is ExceptionGroup: ++ raise TypeError( ++ "Cannot nest BaseExceptions in an ExceptionGroup" ++ ) ++ else: ++ raise TypeError( ++ f"Cannot nest BaseExceptions in {cls.__name__!r}" ++ ) ++ ++ instance = super().__new__(cls, __message, __exceptions) + instance._message = __message +- instance._exceptions = list(__exceptions) ++ instance._exceptions = __exceptions + return instance ++ + def add_note(self, note: str) -> None: + if not isinstance(note, str): + raise TypeError( +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 04d09861d6a071d23c9c2b88b009fe880124f7bb..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -267,10 +267,10 @@ + if num_excs <= max_group_width: + n = num_excs + else: +- n = max_group_width + 0 ++ n = max_group_width + 1 + _ctx.need_close = False + for i in range(n): +- last_exc = i == n - 0 ++ last_exc = i == n - 1 + if last_exc: + # The closing frame may be added by a recursive call + _ctx.need_close = True +@@ -303,6 +303,7 @@ + if is_toplevel: + assert _ctx.exception_group_depth == 1 + _ctx.exception_group_depth = 0 ++ + def format_exception_only(self): + """Format the exception part of the traceback. + The return value is a generator of strings, each ending in a newline. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b5b74d03b010a1a18a664965ef87fd9ed56227c --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/solution/solve.sh @@ -0,0 +1,96 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index e39c9f74e783a6b30a39dd0fb19bc5883e7ff54a..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -56,26 +56,47 @@ + class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): + """A combination of multiple unrelated exceptions.""" + +- def __new__(cls: type[_BaseExceptionGroupSelf], __message: str, +- __exceptions: Sequence[_BaseExceptionT_co]) ->_BaseExceptionGroupSelf: +- """Create a new BaseExceptionGroup instance.""" ++ def __new__( ++ cls: type[_BaseExceptionGroupSelf], ++ __message: str, ++ __exceptions: Sequence[_BaseExceptionT_co], ++ ) -> _BaseExceptionGroupSelf: + if not isinstance(__message, str): +- raise TypeError(f"message must be a string, not {type(__message).__name__}") +- ++ raise TypeError(f"argument 1 must be str, not {type(__message)}") ++ if not isinstance(__exceptions, Sequence): ++ raise TypeError("second argument (exceptions) must be a sequence") + if not __exceptions: +- raise ValueError("exceptions must be a non-empty sequence") +- ++ raise ValueError( ++ "second argument (exceptions) must be a non-empty sequence" ++ ) ++ + for i, exc in enumerate(__exceptions): + if not isinstance(exc, BaseException): +- raise TypeError( +- f"Item {i} of exceptions sequence: expected an exception object, " +- f"got {type(exc).__name__}" ++ raise ValueError( ++ f"Item {i} of second argument (exceptions) is not an exception" + ) +- +- instance = super().__new__(cls) ++ ++ if cls is BaseExceptionGroup: ++ if all(isinstance(exc, Exception) for exc in __exceptions): ++ cls = ExceptionGroup ++ ++ if issubclass(cls, Exception): ++ for exc in __exceptions: ++ if not isinstance(exc, Exception): ++ if cls is ExceptionGroup: ++ raise TypeError( ++ "Cannot nest BaseExceptions in an ExceptionGroup" ++ ) ++ else: ++ raise TypeError( ++ f"Cannot nest BaseExceptions in {cls.__name__!r}" ++ ) ++ ++ instance = super().__new__(cls, __message, __exceptions) + instance._message = __message +- instance._exceptions = list(__exceptions) ++ instance._exceptions = __exceptions + return instance ++ + def add_note(self, note: str) -> None: + if not isinstance(note, str): + raise TypeError( +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 04d09861d6a071d23c9c2b88b009fe880124f7bb..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -267,10 +267,10 @@ + if num_excs <= max_group_width: + n = num_excs + else: +- n = max_group_width + 0 ++ n = max_group_width + 1 + _ctx.need_close = False + for i in range(n): +- last_exc = i == n - 0 ++ last_exc = i == n - 1 + if last_exc: + # The closing frame may be added by a recursive call + _ctx.need_close = True +@@ -303,6 +303,7 @@ + if is_toplevel: + assert _ctx.exception_group_depth == 1 + _ctx.exception_group_depth = 0 ++ + def format_exception_only(self): + """Format the exception part of the traceback. + The return value is a generator of strings, each ending in a newline. +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4705d3270451f688c0c0d286fd9b69e31d95fc84 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:c8802faa2d33fb485669d94da83b6ca4d9317e8549f24bf1f890a8a3c38f18f6" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..f66cc6f8ad6b451f888bbb4b7a3a33cda2affe55 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_suppress.py::test_suppress_exception" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_async_handler", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/first-hunk-only.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..ff53848519a0080f5ac3fb97ac6fd39cfcead68f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/first-hunk-only.sh @@ -0,0 +1,71 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index e39c9f74e783a6b30a39dd0fb19bc5883e7ff54a..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -56,26 +56,47 @@ + class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]): + """A combination of multiple unrelated exceptions.""" + +- def __new__(cls: type[_BaseExceptionGroupSelf], __message: str, +- __exceptions: Sequence[_BaseExceptionT_co]) ->_BaseExceptionGroupSelf: +- """Create a new BaseExceptionGroup instance.""" ++ def __new__( ++ cls: type[_BaseExceptionGroupSelf], ++ __message: str, ++ __exceptions: Sequence[_BaseExceptionT_co], ++ ) -> _BaseExceptionGroupSelf: + if not isinstance(__message, str): +- raise TypeError(f"message must be a string, not {type(__message).__name__}") +- ++ raise TypeError(f"argument 1 must be str, not {type(__message)}") ++ if not isinstance(__exceptions, Sequence): ++ raise TypeError("second argument (exceptions) must be a sequence") + if not __exceptions: +- raise ValueError("exceptions must be a non-empty sequence") +- ++ raise ValueError( ++ "second argument (exceptions) must be a non-empty sequence" ++ ) ++ + for i, exc in enumerate(__exceptions): + if not isinstance(exc, BaseException): +- raise TypeError( +- f"Item {i} of exceptions sequence: expected an exception object, " +- f"got {type(exc).__name__}" ++ raise ValueError( ++ f"Item {i} of second argument (exceptions) is not an exception" + ) +- +- instance = super().__new__(cls) ++ ++ if cls is BaseExceptionGroup: ++ if all(isinstance(exc, Exception) for exc in __exceptions): ++ cls = ExceptionGroup ++ ++ if issubclass(cls, Exception): ++ for exc in __exceptions: ++ if not isinstance(exc, Exception): ++ if cls is ExceptionGroup: ++ raise TypeError( ++ "Cannot nest BaseExceptions in an ExceptionGroup" ++ ) ++ else: ++ raise TypeError( ++ f"Cannot nest BaseExceptions in {cls.__name__!r}" ++ ) ++ ++ instance = super().__new__(cls, __message, __exceptions) + instance._message = __message +- instance._exceptions = list(__exceptions) ++ instance._exceptions = __exceptions + return instance ++ + def add_note(self, note: str) -> None: + if not isinstance(note, str): + raise TypeError( +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__qnop2u5m/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..507d423620983dd018022a3157946109a02d1018 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "86d9d20479db2f1aa8c5825ae73b6c0e1b87bff882bcb1f0b48b7ff5985f272f", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "083e4f98e67149b4389983d445b9e333b7d6ddb6e7b7016f747c3d44fe1b17bf", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "6589d58b5ee2923cfc11fdc66c4dc24099e21eafe663019cdcfbe69b2ab4a244", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "2750f7c388bd518feb6b45219c330cff71f470c1", + "source_completion_sha256": "0ec6674d9ad4043253b50b5c3554b00fe724dc3165e347546526f0a09829dbe9", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "5af60e46dd7f066bf33d8f5858007b2de56b337800241f782fca55c91f3f53b4", + "is_fork": true, + "learner_path": "tasks/55cac8b782ebef1096fe86f9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2750f7c388bd518feb6b45219c330cff71f470c1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "8211158489028bd6338d1ab8bfd0687b638490a68981bf154643bfb38f330bae", + "provenance_path": "tasks/55cac8b782ebef1096fe86f9/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2750f7c388bd518feb6b45219c330cff71f470c1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e939f1ed942290f930fe672c8587d886cf349cce", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "task_sha256": "eb6b62b4f64af92d7c51c86b7817b2fd0cd9f2a106de1c21ef3d206ac52bf0ba", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffdb2c70ab6ed01b050ea25b43e2eaae34e4a841 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/instruction.md @@ -0,0 +1,71 @@ +# ExceptionGroup repr and format_exception_only issues + +#### Description + +I've found two issues with the ExceptionGroup implementation: + +1. The `__repr__` method of `BaseExceptionGroup` has the arguments in the wrong order +2. The `format_exception_only` function doesn't work correctly when called with the old-style arguments (type, value) + +#### Steps/Code to Reproduce + +For the repr issue: +```python +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + +# Create exception groups +group = BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()]) +print(repr(group)) # Incorrect order of arguments + +group = ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')]) +print(repr(group)) # Incorrect order of arguments +``` + +For the format_exception_only issue: +```python +import sys +from exceptiongroup import ExceptionGroup, format_exception_only + +try: + # Create and raise an exception group + raise ExceptionGroup("test message", [ValueError("error1"), RuntimeError("error2")]) +except ExceptionGroup as exc: + # This works fine + output1 = format_exception_only(exc) + print(output1) + + # This doesn't work correctly + output2 = format_exception_only(type(exc), exc) + print(output2) +``` + +#### Expected Results + +For the repr issue: +``` +BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()]) +ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')]) +``` + +For the format_exception_only issue, both calls should produce the same output: +``` +exceptiongroup.ExceptionGroup: test message (2 sub-exceptions) +``` + +#### Actual Results + +For the repr issue, the arguments are in the wrong order: +``` +BaseExceptionGroup([ValueError(1), KeyboardInterrupt()], 'foo') +ExceptionGroup([ValueError(1), RuntimeError('bar')], 'foo') +``` + +For the format_exception_only issue, the old-style call produces incorrect output or an error because it's not handling the type/value arguments correctly. + +#### Versions +Python 3.10.15 +exceptiongroup 1.1.1 + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..dd834726536e29967efd41cf2885e14d25466902 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/metadata.json @@ -0,0 +1,237 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "e939f1ed942290f930fe672c8587d886cf349cce", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "2750f7c388bd518feb6b45219c330cff71f470c1" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch.py", + "/testbed/tests/test_catch_py311.py", + "/testbed/tests/test_suppress.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_exceptions.py", + "tests/test_formatting.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_exceptions.py", + "src/exceptiongroup/_formatting.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 333185, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "5af60e46dd7f066bf33d8f5858007b2de56b337800241f782fca55c91f3f53b4", + "is_fork": true, + "learner_path": "tasks/55cac8b782ebef1096fe86f9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2750f7c388bd518feb6b45219c330cff71f470c1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "8211158489028bd6338d1ab8bfd0687b638490a68981bf154643bfb38f330bae", + "provenance_path": "tasks/55cac8b782ebef1096fe86f9/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2750f7c388bd518feb6b45219c330cff71f470c1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e939f1ed942290f930fe672c8587d886cf349cce", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "task_sha256": "eb6b62b4f64af92d7c51c86b7817b2fd0cd9f2a106de1c21ef3d206ac52bf0ba", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..482970aae63b2ca08c88b90e8d5d586fb9b4ae12 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "86d9d20479db2f1aa8c5825ae73b6c0e1b87bff882bcb1f0b48b7ff5985f272f", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2750f7c388bd518feb6b45219c330cff71f470c1/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "0ec6674d9ad4043253b50b5c3554b00fe724dc3165e347546526f0a09829dbe9", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "09bbc7f67933f5290d85f59f14cd2098a1410bfc1cd38420934275483bdc64ea", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "5af60e46dd7f066bf33d8f5858007b2de56b337800241f782fca55c91f3f53b4", + "is_fork": true, + "learner_path": "tasks/55cac8b782ebef1096fe86f9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2750f7c388bd518feb6b45219c330cff71f470c1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "8211158489028bd6338d1ab8bfd0687b638490a68981bf154643bfb38f330bae", + "provenance_path": "tasks/55cac8b782ebef1096fe86f9/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2750f7c388bd518feb6b45219c330cff71f470c1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "e939f1ed942290f930fe672c8587d886cf349cce", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj", + "task_sha256": "eb6b62b4f64af92d7c51c86b7817b2fd0cd9f2a106de1c21ef3d206ac52bf0ba", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..c224394742b2a9b06388a4055115295b3c885dcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/provided-gold.diff @@ -0,0 +1,26 @@ +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 2762c9d2184d2a25e0161ae42d8870b43ce3f3d1..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -260,7 +260,7 @@ + return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})" + + def __repr__(self) -> str: +- return f"{self.__class__.__name__}({self._exceptions!r}, {self.message!r})" ++ return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})" + + + class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 11f564714706f3b8968f778b96b1843880a8dbc0..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -409,7 +409,7 @@ + + @format_exception_only.register + def _(__exc: type, value: BaseException) -> List[str]: +- return format_exception_only(__exc) ++ return format_exception_only(value) + + + @singledispatch diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4f21a4ebd651af0e13e561c63227da8a67fcce8 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/solution/solve.sh @@ -0,0 +1,32 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 2762c9d2184d2a25e0161ae42d8870b43ce3f3d1..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -260,7 +260,7 @@ + return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})" + + def __repr__(self) -> str: +- return f"{self.__class__.__name__}({self._exceptions!r}, {self.message!r})" ++ return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})" + + + class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 11f564714706f3b8968f778b96b1843880a8dbc0..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -409,7 +409,7 @@ + + @format_exception_only.register + def _(__exc: type, value: BaseException) -> List[str]: +- return format_exception_only(__exc) ++ return format_exception_only(value) + + + @singledispatch +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3a986441073d551aa4475507e0a75e4b5c391f6d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:fb968d6837599a16239731505b6d81b01707eeaf7595e0c5a724f4ce2d303cb3" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..3aa3ac5f88b25c047277425a0227f9c1d99b1ff2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/canaries/first-hunk-only.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..b61e992792f7f70c4c6bda6e35aed4aa1c9ff15c --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 2762c9d2184d2a25e0161ae42d8870b43ce3f3d1..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -260,7 +260,7 @@ + return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})" + + def __repr__(self) -> str: +- return f"{self.__class__.__name__}({self._exceptions!r}, {self.message!r})" ++ return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})" + + + class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception): +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__rrvudskj/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..ed9e61adb320919b7ed8730cb554c74c5e05a49e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "592310476f66e737b71b226104a9b90e7e3dafdb6be0fe164bba9d2c01631d1d", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "f71a548269c38a3897f0f1706e965574e31545dbfee105674ab45055d4e053e8", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "36f82fd12bf2f19c2388d7f42ca2862e6d7a1510ab07076d477080dba08b17b4", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "803e54de0991f1c1ef0204500d50dc6e3dfe9367", + "source_completion_sha256": "28132f7d457c3fc27d524ecbb609f8c431354bf83dff5677ed1438bbb6d60ac8", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "6f62be74bce0f1f74f54b85f4a8e86f673eefc323d03ba2fb5b53e7ccdcf1f89", + "is_fork": true, + "learner_path": "tasks/356a61e3b7a0b2a7437f3ec5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/803e54de0991f1c1ef0204500d50dc6e3dfe9367/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "1952f6eba53d6f7b973a63b48546e9f6c6b4b085fe23018c9df16ff4f5f96f24", + "provenance_path": "tasks/356a61e3b7a0b2a7437f3ec5/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "803e54de0991f1c1ef0204500d50dc6e3dfe9367", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "535430bd835e14986c929a9033b90c9451d2ef5f", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "task_sha256": "9ccae33ea3bf6d532cefbf5bb950255a8cb150efcbde3c75649c806090ad0304", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5a1d41fcba36af732997e6e804e64da409dd1836 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/instruction.md @@ -0,0 +1,31 @@ +ExceptionGroup string representation shows incorrect sub-exception count + +#### Description + +When creating an ExceptionGroup with multiple exceptions, the string representation shows an incorrect count of sub-exceptions. The count appears to be off by one. + +#### Steps/Code to Reproduce + +```python +from exceptiongroup import ExceptionGroup + +# Create an exception group with 2 exceptions +exceptions = [ValueError('foo'), RuntimeError('bar')] +exc_group = ExceptionGroup('test message', exceptions) + +print(str(exc_group)) +# Expected: "test message (2 sub-exceptions)" +# Actual: "test message (1 sub-exception)" + +# Also affects single exception case +single_exc_group = ExceptionGroup('single', [ValueError('single')]) +print(str(single_exc_group)) +# Expected: "single (1 sub-exception)" +# Actual: "single (0 sub-exceptions)" +``` + +The issue also affects exception formatting and traceback display where the count is used. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..1d0aa38eb633c198467fa324ca9070957ccd78de --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/metadata.json @@ -0,0 +1,237 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "535430bd835e14986c929a9033b90c9451d2ef5f", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "803e54de0991f1c1ef0204500d50dc6e3dfe9367" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch_py311.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_suppress.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_catch.py", + "tests/test_formatting.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_exceptions.py", + "src/exceptiongroup/_formatting.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 357279, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "6f62be74bce0f1f74f54b85f4a8e86f673eefc323d03ba2fb5b53e7ccdcf1f89", + "is_fork": true, + "learner_path": "tasks/356a61e3b7a0b2a7437f3ec5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/803e54de0991f1c1ef0204500d50dc6e3dfe9367/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "1952f6eba53d6f7b973a63b48546e9f6c6b4b085fe23018c9df16ff4f5f96f24", + "provenance_path": "tasks/356a61e3b7a0b2a7437f3ec5/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "803e54de0991f1c1ef0204500d50dc6e3dfe9367", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "535430bd835e14986c929a9033b90c9451d2ef5f", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "task_sha256": "9ccae33ea3bf6d532cefbf5bb950255a8cb150efcbde3c75649c806090ad0304", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8031bad72dd852db33acb5eb5a8a46701e4b4b31 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "592310476f66e737b71b226104a9b90e7e3dafdb6be0fe164bba9d2c01631d1d", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/803e54de0991f1c1ef0204500d50dc6e3dfe9367/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "28132f7d457c3fc27d524ecbb609f8c431354bf83dff5677ed1438bbb6d60ac8", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "3c696492344e712b295df7e4dd5c67ef995fadbfcc67da05dc429f526bee69d8", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "6f62be74bce0f1f74f54b85f4a8e86f673eefc323d03ba2fb5b53e7ccdcf1f89", + "is_fork": true, + "learner_path": "tasks/356a61e3b7a0b2a7437f3ec5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/803e54de0991f1c1ef0204500d50dc6e3dfe9367/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "1952f6eba53d6f7b973a63b48546e9f6c6b4b085fe23018c9df16ff4f5f96f24", + "provenance_path": "tasks/356a61e3b7a0b2a7437f3ec5/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "803e54de0991f1c1ef0204500d50dc6e3dfe9367", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "535430bd835e14986c929a9033b90c9451d2ef5f", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd", + "task_sha256": "9ccae33ea3bf6d532cefbf5bb950255a8cb150efcbde3c75649c806090ad0304", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..114bb85acb0e411814cdb22622cb4f53c75942c8 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/provided-gold.diff @@ -0,0 +1,28 @@ +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 4627539dedc6ae96364a65b3871896408638b916..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -256,8 +256,8 @@ + return BaseExceptionGroup(self.message, __excs) + + def __str__(self) -> str: +- suffix = "" if len(self._exceptions) != 1 else "s" +- return f"{self.message} ({len(self._exceptions) - 1} sub-exception{suffix})" ++ suffix = "" if len(self._exceptions) == 1 else "s" ++ return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})" +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 7e41f16683197113dcaa05d664691a7b96c3bf05..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -402,7 +402,7 @@ + def format_exception_only(__exc: BaseException) -> List[str]: + return list( + PatchedTracebackException( +- None, __exc, type(__exc), compact=False ++ type(__exc), __exc, None, compact=True + ).format_exception_only() + ) + diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cb681463e7a3be2c6d5818abbaa7fd6432cb8eef --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/solution/solve.sh @@ -0,0 +1,34 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 4627539dedc6ae96364a65b3871896408638b916..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -256,8 +256,8 @@ + return BaseExceptionGroup(self.message, __excs) + + def __str__(self) -> str: +- suffix = "" if len(self._exceptions) != 1 else "s" +- return f"{self.message} ({len(self._exceptions) - 1} sub-exception{suffix})" ++ suffix = "" if len(self._exceptions) == 1 else "s" ++ return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})" +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 7e41f16683197113dcaa05d664691a7b96c3bf05..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -402,7 +402,7 @@ + def format_exception_only(__exc: BaseException) -> List[str]: + return list( + PatchedTracebackException( +- None, __exc, type(__exc), compact=False ++ type(__exc), __exc, None, compact=True + ).format_exception_only() + ) + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..44d9b997f5967dbcfecf24961c6bac266a5b388b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:2cabb784c400ddbcb672e40c47ac1422d23ca27e3b0dd2f282252ea983f5a2f7" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..5599f2b627b5ef7b96cf7873baf189af860995bb --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/canaries/first-hunk-only.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..936ae9dad8b7051a498e5b095468fe01e0bf70bd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/canaries/first-hunk-only.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 4627539dedc6ae96364a65b3871896408638b916..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -256,8 +256,8 @@ + return BaseExceptionGroup(self.message, __excs) + + def __str__(self) -> str: +- suffix = "" if len(self._exceptions) != 1 else "s" +- return f"{self.message} ({len(self._exceptions) - 1} sub-exception{suffix})" ++ suffix = "" if len(self._exceptions) == 1 else "s" ++ return f"{self.message} ({len(self._exceptions)} sub-exception{suffix})" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({self.message!r}, {self._exceptions!r})" +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__xltm0jpd/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..4cadca6f125be4dc54d8a8f48b98eb6c862eeac3 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "c654e19dbdb9f4c085e307898ba90940c245f71e8d11da9752d766a1d015f26b", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "002d71fb0a6e7153dbb7f82d7c8053d34b579ec9efe440084b0ca8a851417ce6", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "67138beed3ebe2f98347e76ea4c3de3033b9502860cc4441ba588e1a104b9adf", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "80ff0366d0416ed6fc71cf8dd81878fab31f4d09", + "source_completion_sha256": "7edf7e7c0b79cabe3a472b35665bbfa491e470804b79e6dbea1d21c16c98be29", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "b99eaf5290e667d77b6a510761f81e0f4cbacf2153ba3f997e8cb5695f00658b", + "is_fork": true, + "learner_path": "tasks/f86ec420d4dfc60195b7ee0f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/80ff0366d0416ed6fc71cf8dd81878fab31f4d09/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "604b1e5341451a485a4ac03f182f6c0b90768e047f64b5e0fc15b808d584ed6c", + "provenance_path": "tasks/f86ec420d4dfc60195b7ee0f/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "80ff0366d0416ed6fc71cf8dd81878fab31f4d09", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "777a0ef1ab822af417a428076dff1895d9b4cafe", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "task_sha256": "f71dfd9e70baff3932820bb6237863319288131bcb826989c2206f7a65110791", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78d0ed17f695f0955f0ae480321181382b34ca0c --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/instruction.md @@ -0,0 +1,45 @@ +# ExceptionGroup.subgroup() returns incorrect exceptions + +## Description + +When using the `subgroup()` method on an ExceptionGroup, it returns the wrong exceptions. The method seems to be filtering out exceptions that should be included and including exceptions that should be filtered out. + +Here's a simple reproduction case: + +```python +from exceptiongroup import ExceptionGroup + +# Create an exception group with different exception types +eg = ExceptionGroup("test group", [ + ValueError("value error"), + TypeError("type error"), + RuntimeError("runtime error") +]) + +# Try to get a subgroup of only ValueError exceptions +# This should return a group with just the ValueError +# but it returns the opposite (everything except ValueError) +subgroup = eg.subgroup(ValueError) + +print(f"Subgroup exceptions: {[type(e).__name__ for e in subgroup.exceptions]}") +# Expected: ['ValueError'] +# Actual: ['TypeError', 'RuntimeError'] +``` + +The same issue happens when using a predicate function: + +```python +# This should return exceptions where the predicate is True +# but it returns exceptions where the predicate is False +subgroup = eg.subgroup(lambda e: isinstance(e, ValueError)) + +print(f"Subgroup exceptions: {[type(e).__name__ for e in subgroup.exceptions]}") +# Expected: ['ValueError'] +# Actual: ['TypeError', 'RuntimeError'] +``` + +This affects all methods that rely on `subgroup()`, including the `split()` method. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..993224bfa33c2e60d56f65747dce6c0029578024 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/metadata.json @@ -0,0 +1,237 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_formatting_syntax_error" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "777a0ef1ab822af417a428076dff1895d9b4cafe", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "80ff0366d0416ed6fc71cf8dd81878fab31f4d09" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch.py", + "/testbed/tests/test_catch_py311.py", + "/testbed/tests/test_suppress.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_exceptions.py", + "tests/test_formatting.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_exceptions.py", + "src/exceptiongroup/_formatting.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 333191, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "b99eaf5290e667d77b6a510761f81e0f4cbacf2153ba3f997e8cb5695f00658b", + "is_fork": true, + "learner_path": "tasks/f86ec420d4dfc60195b7ee0f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/80ff0366d0416ed6fc71cf8dd81878fab31f4d09/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "604b1e5341451a485a4ac03f182f6c0b90768e047f64b5e0fc15b808d584ed6c", + "provenance_path": "tasks/f86ec420d4dfc60195b7ee0f/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "80ff0366d0416ed6fc71cf8dd81878fab31f4d09", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "777a0ef1ab822af417a428076dff1895d9b4cafe", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "task_sha256": "f71dfd9e70baff3932820bb6237863319288131bcb826989c2206f7a65110791", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ab8d0a60bee50b60e5d242b8ef7a65b51f70d2ad --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c654e19dbdb9f4c085e307898ba90940c245f71e8d11da9752d766a1d015f26b", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/80ff0366d0416ed6fc71cf8dd81878fab31f4d09/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "7edf7e7c0b79cabe3a472b35665bbfa491e470804b79e6dbea1d21c16c98be29", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "28ac77cd7909d3dadf3efc34e3396d40b3b391b1b6adac1d243535822cc29ce7", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "b99eaf5290e667d77b6a510761f81e0f4cbacf2153ba3f997e8cb5695f00658b", + "is_fork": true, + "learner_path": "tasks/f86ec420d4dfc60195b7ee0f/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/80ff0366d0416ed6fc71cf8dd81878fab31f4d09/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "604b1e5341451a485a4ac03f182f6c0b90768e047f64b5e0fc15b808d584ed6c", + "provenance_path": "tasks/f86ec420d4dfc60195b7ee0f/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "80ff0366d0416ed6fc71cf8dd81878fab31f4d09", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "777a0ef1ab822af417a428076dff1895d9b4cafe", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl", + "task_sha256": "f71dfd9e70baff3932820bb6237863319288131bcb826989c2206f7a65110791", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..ac15f05a4b9626f43716b019a8139fe8dc4474da --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/provided-gold.diff @@ -0,0 +1,37 @@ +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 09a2e55dd5bd63b260ace729fa327d3e0c6f0af0..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -155,9 +155,9 @@ + if subgroup is not exc: + modified = True + elif condition(exc): ++ exceptions.append(exc) ++ else: + modified = True +- else: +- exceptions.append(exc) + + if not modified: + return self +@@ -166,6 +166,7 @@ + return group + else: + return None ++ + @overload + def split( + self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...] +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index a123d5920aa8ee892ab93b20d4ff60f031b0a62f..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -68,7 +68,7 @@ + def exceptiongroup_excepthook( + etype: type[BaseException], value: BaseException, tb: TracebackType | None + ) -> None: +- sys.stdout.write("".join(traceback.format_exception(etype, value, tb[1:]))) ++ sys.stderr.write("".join(traceback.format_exception(etype, value, tb))) + + + class PatchedTracebackException(traceback.TracebackException): diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4446ddde8cffe3155e1d778d47daf6a272ecbe77 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/solution/solve.sh @@ -0,0 +1,43 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 09a2e55dd5bd63b260ace729fa327d3e0c6f0af0..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -155,9 +155,9 @@ + if subgroup is not exc: + modified = True + elif condition(exc): ++ exceptions.append(exc) ++ else: + modified = True +- else: +- exceptions.append(exc) + + if not modified: + return self +@@ -166,6 +166,7 @@ + return group + else: + return None ++ + @overload + def split( + self, __condition: type[_ExceptionT] | tuple[type[_ExceptionT], ...] +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index a123d5920aa8ee892ab93b20d4ff60f031b0a62f..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -68,7 +68,7 @@ + def exceptiongroup_excepthook( + etype: type[BaseException], value: BaseException, tb: TracebackType | None + ) -> None: +- sys.stdout.write("".join(traceback.format_exception(etype, value, tb[1:]))) ++ sys.stderr.write("".join(traceback.format_exception(etype, value, tb))) + + + class PatchedTracebackException(traceback.TracebackException): +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d9f0f6125dffffbba5fbe4a898f0ae53e75c9bb --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:95dffab5d64c9e3da9078e4c2a6bcd5333b55b64db356a385c36e3711eae8b27" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..c80b0562aaa1a50ecb8ccdb79418762cd5dd7ae2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_formatting_syntax_error" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/canaries/first-hunk-only.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..e45ca8c0eece2f0abb84733b8d01edaa1dd7a282 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/canaries/first-hunk-only.sh @@ -0,0 +1,22 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 09a2e55dd5bd63b260ace729fa327d3e0c6f0af0..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -155,9 +155,9 @@ + if subgroup is not exc: + modified = True + elif condition(exc): ++ exceptions.append(exc) ++ else: + modified = True +- else: +- exceptions.append(exc) + + if not modified: + return self +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__yj0e8azl/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..aa55e0d8286def6cabe9b29e7af237f40520c433 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "c19414246ab81fb50a8e81fa8a0cfc233021b679dd6440a98d912658b9b6c276", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8897fab8e2622bf7cc28a0809039ade69d6c4bf27f83526fe76f1d09820b62e1", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": true, + "partial_repair_sha256": "396dfa203ecd770aca6add680e079c7b0f51dd74a9525032d6a1c9b71b9dac3f", + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "d338f656f4b53226eb6e83bafa470f0f4862efea", + "source_completion_sha256": "741c1805a1b114710c730461b067065786630f071d108b4f079e642a22337314", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "0d264b13287827b5cd7f10fe009a399dbe9863400318f666713a7f9e8d5d892c", + "is_fork": true, + "learner_path": "tasks/2766b58adc5aaa6bb0efd6b8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/d338f656f4b53226eb6e83bafa470f0f4862efea/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "e068606f74b68f4adb820642675ed7176e58a782245740a59026e63517aa41ea", + "provenance_path": "tasks/2766b58adc5aaa6bb0efd6b8/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d338f656f4b53226eb6e83bafa470f0f4862efea", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "94fa2106b70cd38a789718f50aebf93127de7930", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "task_sha256": "2a46507fcde248582d9274f117763448df0b12c40776708c7363d1131be52676", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..218028d27412a4e265fc3637f23c8a133487589d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/instruction.md @@ -0,0 +1,37 @@ +# BaseExceptionGroup.derive() method changes message and order of exceptions + +## Description + +Currently, the `derive()` method in `BaseExceptionGroup` is modifying both the message and the order of exceptions when creating a new exception group. This breaks several functionalities that rely on the derived exception group maintaining the same message and order as the original. + +When using methods like `subgroup()`, `split()`, or the `catch()` context manager, the resulting exception groups have their messages converted to uppercase and their exceptions reversed in order. This is unexpected behavior and breaks code that relies on the original ordering and message formatting. + +## Reproduction + +Here's a simple example that demonstrates the issue: + +```python +from exceptiongroup import ExceptionGroup + +# Create an exception group with multiple exceptions +eg = ExceptionGroup("test message", [ + ValueError("first"), + RuntimeError("second"), + TypeError("third") +]) + +# Use subgroup to extract some exceptions +subeg = eg.subgroup(lambda e: isinstance(e, (ValueError, RuntimeError))) + +# The message is now uppercase and exceptions are in reverse order +print(subeg) # TEST MESSAGE (2 sub-exceptions) +print(subeg.exceptions) # [RuntimeError('second'), ValueError('first')] +``` + +The expected behavior would be for the derived exception group to maintain the same message case and exception order as the original. + +Additionally, there appears to be an issue with exception notes not being properly displayed in the formatted output of exception groups. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..87139f137ea08d763382e9698917d66a25d02954 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/metadata.json @@ -0,0 +1,237 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "94fa2106b70cd38a789718f50aebf93127de7930", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "d338f656f4b53226eb6e83bafa470f0f4862efea" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch_py311.py", + "/testbed/tests/test_suppress.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_catch.py", + "tests/test_exceptions.py", + "tests/test_formatting.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_exceptions.py", + "src/exceptiongroup/_formatting.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 325762, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "0d264b13287827b5cd7f10fe009a399dbe9863400318f666713a7f9e8d5d892c", + "is_fork": true, + "learner_path": "tasks/2766b58adc5aaa6bb0efd6b8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/d338f656f4b53226eb6e83bafa470f0f4862efea/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "e068606f74b68f4adb820642675ed7176e58a782245740a59026e63517aa41ea", + "provenance_path": "tasks/2766b58adc5aaa6bb0efd6b8/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d338f656f4b53226eb6e83bafa470f0f4862efea", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "94fa2106b70cd38a789718f50aebf93127de7930", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "task_sha256": "2a46507fcde248582d9274f117763448df0b12c40776708c7363d1131be52676", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f71e2f98b0bbf8f34a30acee79febb613874ebd6 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "c19414246ab81fb50a8e81fa8a0cfc233021b679dd6440a98d912658b9b6c276", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/d338f656f4b53226eb6e83bafa470f0f4862efea/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "741c1805a1b114710c730461b067065786630f071d108b4f079e642a22337314", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "cd26a4c6d0660b0ae572357b90f2a404481838f0f71f113c45053705999f76bb", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "0d264b13287827b5cd7f10fe009a399dbe9863400318f666713a7f9e8d5d892c", + "is_fork": true, + "learner_path": "tasks/2766b58adc5aaa6bb0efd6b8/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/d338f656f4b53226eb6e83bafa470f0f4862efea/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "e068606f74b68f4adb820642675ed7176e58a782245740a59026e63517aa41ea", + "provenance_path": "tasks/2766b58adc5aaa6bb0efd6b8/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "d338f656f4b53226eb6e83bafa470f0f4862efea", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "94fa2106b70cd38a789718f50aebf93127de7930", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno", + "task_sha256": "2a46507fcde248582d9274f117763448df0b12c40776708c7363d1131be52676", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..df8c5a28714e52d216934c9c1b253a8f333fc182 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/provided-gold.diff @@ -0,0 +1,31 @@ +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 138c0edb9fd69978bcd042e5c801fa013dd29de3..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -253,7 +253,7 @@ + def derive( + self, __excs: Sequence[_BaseExceptionT] + ) -> BaseExceptionGroup[_BaseExceptionT]: +- return BaseExceptionGroup(self.message.upper(), __excs[::-1]) ++ return BaseExceptionGroup(self.message, __excs) + + def __str__(self) -> str: + suffix = "" if len(self._exceptions) == 1 else "s" +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 7aa2679a8f531e7622e461bacba4c8b7e1bd9ef6..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -333,9 +333,12 @@ + yield from traceback_exception_original_format_exception_only(self) + + if isinstance(self.__notes__, collections.abc.Sequence): +- pass ++ for note in self.__notes__: ++ note = _safe_string(note, "note") ++ yield from [line + "\n" for line in note.split("\n")] + elif self.__notes__ is not None: + yield _safe_string(self.__notes__, "__notes__", func=repr) ++ + + traceback_exception_original_format = traceback.TracebackException.format + traceback_exception_original_format_exception_only = ( diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7114eefb820b552fe1be38c6f9f6eff44d04cea2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/solution/solve.sh @@ -0,0 +1,37 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 138c0edb9fd69978bcd042e5c801fa013dd29de3..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -253,7 +253,7 @@ + def derive( + self, __excs: Sequence[_BaseExceptionT] + ) -> BaseExceptionGroup[_BaseExceptionT]: +- return BaseExceptionGroup(self.message.upper(), __excs[::-1]) ++ return BaseExceptionGroup(self.message, __excs) + + def __str__(self) -> str: + suffix = "" if len(self._exceptions) == 1 else "s" +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 7aa2679a8f531e7622e461bacba4c8b7e1bd9ef6..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -333,9 +333,12 @@ + yield from traceback_exception_original_format_exception_only(self) + + if isinstance(self.__notes__, collections.abc.Sequence): +- pass ++ for note in self.__notes__: ++ note = _safe_string(note, "note") ++ yield from [line + "\n" for line in note.split("\n")] + elif self.__notes__ is not None: + yield _safe_string(self.__notes__, "__notes__", func=repr) ++ + + traceback_exception_original_format = traceback.TracebackException.format + traceback_exception_original_format_exception_only = ( +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76dc594bc94ce8bf476cd89edb32c5afdae3403c --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:0dbe03e520a99b82be54dfec6c0b0ab5b1c93730294edca57658eb5c9f4c93fe" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..2a24c4a06dec8d2eef84a5b13d17fd8a02023b63 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/canaries/first-hunk-only.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/canaries/first-hunk-only.sh new file mode 100644 index 0000000000000000000000000000000000000000..b48a09e51acebc398b696c9411cad0c815d76ee0 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/canaries/first-hunk-only.sh @@ -0,0 +1,19 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_PARTIAL' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 138c0edb9fd69978bcd042e5c801fa013dd29de3..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -253,7 +253,7 @@ + def derive( + self, __excs: Sequence[_BaseExceptionT] + ) -> BaseExceptionGroup[_BaseExceptionT]: +- return BaseExceptionGroup(self.message.upper(), __excs[::-1]) ++ return BaseExceptionGroup(self.message, __excs) + + def __str__(self) -> str: + suffix = "" if len(self._exceptions) == 1 else "s" +OPENENV_PARTIAL +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.combine_module__ytjqxjno/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..1dc3efd41ee82f97d16915bd7e88b2750f9c2ca9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "a7e9995da8ab99bc895971e369daa0671141bfa9e2dffcfc5b61a2f7ed8b78fb", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "8ff879e8fcb63c6291a959457feecf99b52db01a4dc7428b25556d88ea85b3f3", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "2059f5b5d883446542b419eee61a89f54ccf6233", + "source_completion_sha256": "99c0b6b23967a1ffdf306d2ef74a064c471101d240e450791916a7d2cb9068bf", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "c27a5c6031cfa1921d3495f48f6f7fe3999bf7c15a47280db0bd820d652cc104", + "is_fork": true, + "learner_path": "tasks/bc1f39568f863924bea2cdc5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2059f5b5d883446542b419eee61a89f54ccf6233/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "d93e66e7554686bc6394b108ac9525bb8781ae78ed4a41ec412fe3886db57254", + "provenance_path": "tasks/bc1f39568f863924bea2cdc5/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2059f5b5d883446542b419eee61a89f54ccf6233", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bb87ca4513fa6f80d0429b4dff8c1cfb04873ed0", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "task_sha256": "050b46e7261aa65fd698202040b76017d3340ecd0fba4950740b4f2e94fa6d2d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c3dae5fe012e41fcdda44a0b0eeae4c3813d987 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/instruction.md @@ -0,0 +1,43 @@ +ExceptionGroup constructor arguments swapped causing TypeError + +#### Description + +When creating an ExceptionGroup, the constructor arguments appear to be swapped internally, causing TypeErrors when trying to create exception groups with valid arguments. + +#### Steps/Code to Reproduce + +```python +from exceptiongroup import ExceptionGroup + +# This should work but raises TypeError +try: + eg = ExceptionGroup("test message", [ValueError("error1"), RuntimeError("error2")]) + print("Created successfully:", eg) +except Exception as e: + print("Error:", e) + +# Even basic creation fails +try: + eg = ExceptionGroup("simple", [Exception("test")]) + print("Simple creation:", eg) +except Exception as e: + print("Simple error:", e) +``` + +The error messages suggest the constructor is expecting the arguments in the wrong order - it's treating the message as if it should be a sequence and the exceptions list as if it should be a string. + +#### Expected Behavior + +ExceptionGroup should accept a string message as the first argument and a sequence of exceptions as the second argument, as documented. + +#### Actual Behavior + +TypeError is raised with messages like: +- "argument 2 must be str, not " +- "first argument (message) must be a sequence" + +This suggests the internal validation logic has the arguments backwards. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..9a837d6f55671306fb469c1e352e143b13073e9c --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/metadata.json @@ -0,0 +1,236 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_suppress.py::test_suppress_exception" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "bb87ca4513fa6f80d0429b4dff8c1cfb04873ed0", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "2059f5b5d883446542b419eee61a89f54ccf6233" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch_py311.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_catch.py", + "tests/test_exceptions.py", + "tests/test_formatting.py", + "tests/test_suppress.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_exceptions.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 325260, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "c27a5c6031cfa1921d3495f48f6f7fe3999bf7c15a47280db0bd820d652cc104", + "is_fork": true, + "learner_path": "tasks/bc1f39568f863924bea2cdc5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2059f5b5d883446542b419eee61a89f54ccf6233/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "d93e66e7554686bc6394b108ac9525bb8781ae78ed4a41ec412fe3886db57254", + "provenance_path": "tasks/bc1f39568f863924bea2cdc5/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2059f5b5d883446542b419eee61a89f54ccf6233", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bb87ca4513fa6f80d0429b4dff8c1cfb04873ed0", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "task_sha256": "050b46e7261aa65fd698202040b76017d3340ecd0fba4950740b4f2e94fa6d2d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4f5f24b6f8cb695ad098784dfc4543983418dd0b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "a7e9995da8ab99bc895971e369daa0671141bfa9e2dffcfc5b61a2f7ed8b78fb", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2059f5b5d883446542b419eee61a89f54ccf6233/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "99c0b6b23967a1ffdf306d2ef74a064c471101d240e450791916a7d2cb9068bf", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "1ee237f832f062fe104fb99ec21009b92a8d525c052cebcbbfbf4a8b94978905", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "c27a5c6031cfa1921d3495f48f6f7fe3999bf7c15a47280db0bd820d652cc104", + "is_fork": true, + "learner_path": "tasks/bc1f39568f863924bea2cdc5/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/2059f5b5d883446542b419eee61a89f54ccf6233/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "d93e66e7554686bc6394b108ac9525bb8781ae78ed4a41ec412fe3886db57254", + "provenance_path": "tasks/bc1f39568f863924bea2cdc5/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "2059f5b5d883446542b419eee61a89f54ccf6233", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "bb87ca4513fa6f80d0429b4dff8c1cfb04873ed0", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q", + "task_sha256": "050b46e7261aa65fd698202040b76017d3340ecd0fba4950740b4f2e94fa6d2d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..99d035f468c6c34f9518c9a1e697465e182253b1 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/provided-gold.diff @@ -0,0 +1,58 @@ +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 3d260feca07c462e295aa29b7959ec18cefa0712..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -61,36 +61,40 @@ + __message: str, + __exceptions: Sequence[_BaseExceptionT_co], + ) -> _BaseExceptionGroupSelf: +- if not isinstance(__exceptions, str): +- raise TypeError(f"argument 2 must be str, not {type(__exceptions)}") +- if not isinstance(__message, Sequence): +- raise TypeError("first argument (message) must be a sequence") ++ if not isinstance(__message, str): ++ raise TypeError(f"argument 1 must be str, not {type(__message)}") ++ if not isinstance(__exceptions, Sequence): ++ raise TypeError("second argument (exceptions) must be a sequence") + if not __exceptions: + raise ValueError( + "second argument (exceptions) must be a non-empty sequence" + ) + + for i, exc in enumerate(__exceptions): +- if not isinstance(exc, Exception): ++ if not isinstance(exc, BaseException): + raise ValueError( + f"Item {i} of second argument (exceptions) is not an exception" + ) + +- if cls is not BaseExceptionGroup: +- if not any(isinstance(exc, BaseException) for exc in __exceptions): ++ if cls is BaseExceptionGroup: ++ if all(isinstance(exc, Exception) for exc in __exceptions): + cls = ExceptionGroup + +- if issubclass(cls, BaseException): ++ if issubclass(cls, Exception): + for exc in __exceptions: +- if isinstance(exc, Exception): +- if cls is not ExceptionGroup: ++ if not isinstance(exc, Exception): ++ if cls is ExceptionGroup: + raise TypeError( +- "Cannot nest Exceptions in an BaseExceptionGroup" ++ "Cannot nest BaseExceptions in an ExceptionGroup" + ) ++ else: ++ raise TypeError( ++ f"Cannot nest BaseExceptions in {cls.__name__!r}" ++ ) + + instance = super().__new__(cls, __message, __exceptions) +- instance._exceptions = __message +- instance._message = __exceptions ++ instance._message = __message ++ instance._exceptions = __exceptions + return instance + + def add_note(self, note: str) -> None: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1541d327ea151c7012fa3aadd249685f36d3f5ef --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/solution/solve.sh @@ -0,0 +1,64 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_exceptions.py b/src/exceptiongroup/_exceptions.py +index 3d260feca07c462e295aa29b7959ec18cefa0712..a4a7acea822d43ba91183cff0b44f31313171d1a 100644 +--- a/src/exceptiongroup/_exceptions.py ++++ b/src/exceptiongroup/_exceptions.py +@@ -61,36 +61,40 @@ + __message: str, + __exceptions: Sequence[_BaseExceptionT_co], + ) -> _BaseExceptionGroupSelf: +- if not isinstance(__exceptions, str): +- raise TypeError(f"argument 2 must be str, not {type(__exceptions)}") +- if not isinstance(__message, Sequence): +- raise TypeError("first argument (message) must be a sequence") ++ if not isinstance(__message, str): ++ raise TypeError(f"argument 1 must be str, not {type(__message)}") ++ if not isinstance(__exceptions, Sequence): ++ raise TypeError("second argument (exceptions) must be a sequence") + if not __exceptions: + raise ValueError( + "second argument (exceptions) must be a non-empty sequence" + ) + + for i, exc in enumerate(__exceptions): +- if not isinstance(exc, Exception): ++ if not isinstance(exc, BaseException): + raise ValueError( + f"Item {i} of second argument (exceptions) is not an exception" + ) + +- if cls is not BaseExceptionGroup: +- if not any(isinstance(exc, BaseException) for exc in __exceptions): ++ if cls is BaseExceptionGroup: ++ if all(isinstance(exc, Exception) for exc in __exceptions): + cls = ExceptionGroup + +- if issubclass(cls, BaseException): ++ if issubclass(cls, Exception): + for exc in __exceptions: +- if isinstance(exc, Exception): +- if cls is not ExceptionGroup: ++ if not isinstance(exc, Exception): ++ if cls is ExceptionGroup: + raise TypeError( +- "Cannot nest Exceptions in an BaseExceptionGroup" ++ "Cannot nest BaseExceptions in an ExceptionGroup" + ) ++ else: ++ raise TypeError( ++ f"Cannot nest BaseExceptions in {cls.__name__!r}" ++ ) + + instance = super().__new__(cls, __message, __exceptions) +- instance._exceptions = __message +- instance._message = __exceptions ++ instance._message = __message ++ instance._exceptions = __exceptions + return instance + + def add_note(self, note: str) -> None: +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d3b74373431c0edf4b2dae23a6159840a19b4d2d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:2b9dee2ff8e523feeb7e484af4ca758089ca1a9d0dbf39c439f0ddf80eebc4d3" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..b3809891e8d9fb85353ef220f3d5b7a196558b5e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_suppress.py::test_suppress_exception" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_nested", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4njcbj1q/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/LICENSE.source b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/LICENSE.source new file mode 100644 index 0000000000000000000000000000000000000000..50d4fa5e68439ce837f6eef437b299c0dd7c8594 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/LICENSE.source @@ -0,0 +1,73 @@ +The MIT License (MIT) + +Copyright (c) 2022 Alex Grönholm + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +This project contains code copied from the Python standard library. +The following is the required license notice for those parts. + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/adapter.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/adapter.json new file mode 100644 index 0000000000000000000000000000000000000000..df811438346e7b249d8b16b8f8210d533280d0e3 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/adapter.json @@ -0,0 +1,133 @@ +{ + "canary_selection": "Fixed first provided gold hunk only when at least2hunks exist; strict subset, never reward-selected. Single-hunk task original-bug canary is explicitly NOP-equivalent and adds no signal beyond floor_gap.", + "collector_sha256": "352e555112f2de8a1393f939903e4971c9ace0e944843762b707a725c5c72481", + "dependency_installation_pinned": false, + "dependency_setup_sha256": "6780ef55e5987924663b6e2b917a1b319de74c1108bf39a9fe6f5dc719935dfe", + "gold_patch_sha256": "90fe57463b966f571cdb7dee320583ce7efa21df79d6f304fbd56967e40dcec2", + "hostile_code_isolation_established": false, + "known_wrong_semantic_implementations": 0, + "native_inventory_sha256": "fc7c0a5be6b3d0ee37e93d146294085abc8ede49f5f17bbe6c49a89e42cdb079", + "new_files_deletions_and_executable_modes_supported": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_bug_canary_nop_equivalent": true, + "original_bug_runtime_wrongness_established": false, + "partial_repair_canary": false, + "partial_repair_sha256": null, + "partial_repair_wrongness_established": false, + "positive_approval_policy": "All original strict presence/identity/no-skip/no-error/exit checks retained", + "private_checker_sha256": "f0a641064b725415e23a0221bb53c90446d7efcb7f9ece5ede93a220d18dd9e7", + "private_checker_version": "matched-failure-precedence-v2", + "provided_original_bug_control": true, + "repo_url": "https://github.com/swesmith/agronholm__exceptiongroup.0b4f4937.git", + "runtime_image": null, + "runtime_ready": false, + "runtime_recipe": { + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } + }, + "runtime_resource_review_required": false, + "schema": "python-git-patch-jobs-v1", + "source_base_commit": "a869eb3e2155743e2b3e307fa943dea76294c5d1", + "source_completion_sha256": "32d1051b30599d00fd770f37af14e53c33cbce88e00b2c6a54385ebdd9840831", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_pr_url": null, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "d568355f1e6bff822af57fd8e4a91b6692090f526543933bed5ac9780bef924e", + "is_fork": true, + "learner_path": "tasks/8c86f05641232d68734e78a9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/a869eb3e2155743e2b3e307fa943dea76294c5d1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "a9ce60684d8b12e4bedfec008ce9f3003fe7d31aeb20d5d4d714c212b6d8403b", + "provenance_path": "tasks/8c86f05641232d68734e78a9/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a869eb3e2155743e2b3e307fa943dea76294c5d1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2239deee3315c003206967c18418544aad587514", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "task_sha256": "9c22d7b44fb4074d808ba1dd3e0d032db429438eefa6f5c95538835e55d84f61", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "symlink_submodule_changes_supported": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "transfer": "index-independent-worktree-to-Git-binary-patch", + "transfer_path": "/testbed/submission.patch", + "upstream_repo": "agronholm/exceptiongroup" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/dependency-setup.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/dependency-setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..301f0c85db1d652100a14842ae536250e9f594a9 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/dependency-setup.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +python -c 'import sys; assert sys.version_info[:2] == (3, 10)' +python -m pip install pytest==8.4.2 +python -m pip install -e . +python -m pip install -e '.[test]' diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/environment/Dockerfile b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a59b58c2ea8217c78c1e39b4678f93c8c0023bcd --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/environment/Dockerfile @@ -0,0 +1,3 @@ +# Runtime is selected only by an independently qualified immutable amd64 receipt. +FROM ubuntu:22.04 +RUN false diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/instruction.md b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b0485a376365792803cdea0c94addcd81db2b7f1 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/instruction.md @@ -0,0 +1,25 @@ +# Incorrect formatting of nested exception groups + +The formatting of nested exception groups is broken. When trying to format a nested exception group, the output is incorrect. + +Here's a simple reproduction script: + +```python +from exceptiongroup import ExceptionGroup + +try: + try: + raise ValueError("Inner error") + except Exception as e: + raise ExceptionGroup("Inner group", [e]) +except Exception as outer_e: + raise ExceptionGroup("Outer group", [outer_e]) +``` + +When this code runs, the formatting of the nested exception groups is incorrect. The compact formatting is not being applied correctly and the chain parameter is being inverted, causing the traceback to be displayed incorrectly. + +This affects any code that relies on proper formatting of nested exception groups, which can make debugging more difficult when dealing with complex exception hierarchies. + +## Environment + +The repository is at `/testbed/repo`. Its dependencies, including pytest, are installed in the `testbed` conda environment, which comes first on PATH. If `python -m pytest` reports that pytest is missing, use the full interpreter path: `/opt/miniconda3/envs/testbed/bin/python -m pytest `. Don't install packages: the tests need nothing else, and the sandbox may have no network access. diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/metadata.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/metadata.json new file mode 100644 index 0000000000000000000000000000000000000000..4c4473b0e719f825d832a03869cad0fb3ca66431 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/metadata.json @@ -0,0 +1,236 @@ +{ + "all_runtime_and_training_flags": false, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_healthy_reference_proof": { + "FAIL_TO_PASS": [ + "tests/test_formatting.py::test_format_nested" + ], + "PASS_TO_PASS": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ], + "all_git_blobs_modes_verified": true, + "cloud_launch_ready": false, + "commits": { + "bug": "2239deee3315c003206967c18418544aad587514", + "healthy": "2afba2eefd1899b919eac83e3e73360deca0d473", + "learner": "a869eb3e2155743e2b3e307fa943dea76294c5d1" + }, + "existing_squirrel_snapshot_reused": false, + "full_transfer_allowlist": [ + "/testbed/.github/ISSUE_TEMPLATE/bug_report.yaml", + "/testbed/.github/ISSUE_TEMPLATE/config.yml", + "/testbed/.github/ISSUE_TEMPLATE/features_request.yaml", + "/testbed/.gitignore", + "/testbed/.pre-commit-config.yaml", + "/testbed/CHANGES.rst", + "/testbed/LICENSE", + "/testbed/README.rst", + "/testbed/pyproject.toml", + "/testbed/src/exceptiongroup/__init__.py", + "/testbed/src/exceptiongroup/_catch.py", + "/testbed/src/exceptiongroup/_exceptions.py", + "/testbed/src/exceptiongroup/_formatting.py", + "/testbed/src/exceptiongroup/_suppress.py", + "/testbed/src/exceptiongroup/py.typed", + "/testbed/tests/__init__.py", + "/testbed/tests/apport_excepthook.py", + "/testbed/tests/check_types.py", + "/testbed/tests/conftest.py", + "/testbed/tests/test_apport_monkeypatching.py", + "/testbed/tests/test_catch.py", + "/testbed/tests/test_catch_py311.py", + "/testbed/tests/test_exceptions.py", + "/testbed/tests/test_suppress.py" + ], + "healthy_stage_meaning": "Direct parent of the mutation; no source or test execution has been performed", + "mutation_matches_dataset_and_git_blobs": true, + "official_profile": { + "eval_sets": [], + "profile_class": "Exceptiongroup0b4f4937", + "profile_lines": [ + 327, + 330 + ], + "profile_source_commit": "9b74ac08118a85c39c356802f7961893af73e07f", + "profile_source_path": "swesmith/profiles/python.py", + "profile_source_sha256": "eadf29551ca2e706950d3f2311b47a3d08c2ccee3c8dd217fa299014a08e4286", + "upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "upstream_repo": "agronholm/exceptiongroup" + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "private_test_paths": [ + "tests/test_formatting.py" + ], + "private_tests_unchanged": true, + "profile_mapping_basis": "Explicit upstream repo and full commit fields parsed from pinned official Python profile AST, not basename inference", + "qwen_calibrated": false, + "runtime_qualified": false, + "source_paths": [ + "src/exceptiongroup/_formatting.py" + ], + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_stages_bytes": 364442, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "transfer_limitation": "Existing regular files only; new arbitrary file additions need a qualified patch adapter", + "upstream_repo": "agronholm/exceptiongroup" + }, + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "d568355f1e6bff822af57fd8e4a91b6692090f526543933bed5ac9780bef924e", + "is_fork": true, + "learner_path": "tasks/8c86f05641232d68734e78a9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/a869eb3e2155743e2b3e307fa943dea76294c5d1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "a9ce60684d8b12e4bedfec008ce9f3003fe7d31aeb20d5d4d714c212b6d8403b", + "provenance_path": "tasks/8c86f05641232d68734e78a9/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a869eb3e2155743e2b3e307fa943dea76294c5d1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2239deee3315c003206967c18418544aad587514", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "task_sha256": "9c22d7b44fb4074d808ba1dd3e0d032db429438eefa6f5c95538835e55d84f61", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_kind": "original-source-mutation" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/provenance.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..01deddbb8125fb247ae8e74eb1873fb87518e78d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/provenance.json @@ -0,0 +1,88 @@ +{ + "generated_reference": false, + "healthy_reference_delta_sha256": "90fe57463b966f571cdb7dee320583ce7efa21df79d6f304fbd56967e40dcec2", + "native_pytest_ids_preserved": true, + "original_source_code_license": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/a869eb3e2155743e2b3e307fa943dea76294c5d1/LICENSE" + }, + "provided_reference": true, + "qwen_calibrated": false, + "runtime_qualified": false, + "source_completion_sha256": "32d1051b30599d00fd770f37af14e53c33cbce88e00b2c6a54385ebdd9840831", + "source_index_sha256": "e856874b9410fce9f3bfea52c8c482e84b3e43942d87517f8b55f0034bd40f6f", + "source_proof_sha256": "625afc625dacdb8a0fa5f83eb60349537691a1e78e642f596fb024ff5fc70a40", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-py:agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "cloud_launch_ready": false, + "eligibility": { + "reasons": [], + "semantic_nonoverlap_established": false, + "status": "eligible_for_controls", + "training_admissible": false, + "warnings": [] + }, + "healthy_mirror_commit": "2afba2eefd1899b919eac83e3e73360deca0d473", + "instruction_sha256": "d568355f1e6bff822af57fd8e4a91b6692090f526543933bed5ac9780bef924e", + "is_fork": true, + "learner_path": "tasks/8c86f05641232d68734e78a9/learner", + "license_evidence": { + "source_code": { + "actual_upstream_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "actual_upstream_url": "https://raw.githubusercontent.com/agronholm/exceptiongroup/0b4f49378b585a338ae10abd72ec2006c5057d7b/LICENSE", + "reviewed": true, + "sha256": "6e5070d765031e0ad403a1cbf90ae6d19a0228f802e320b7acff460aa72ed47c", + "spdx": "MIT", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/agronholm__exceptiongroup.0b4f4937/a869eb3e2155743e2b3e307fa943dea76294c5d1/LICENSE" + }, + "task_bundle": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + } + }, + "original_source_commit": "0b4f49378b585a338ae10abd72ec2006c5057d7b", + "patch_sha256": "a9ce60684d8b12e4bedfec008ce9f3003fe7d31aeb20d5d4d714c212b6d8403b", + "provenance_path": "tasks/8c86f05641232d68734e78a9/source-proof.json", + "repository_lineage": [ + "swesmith/agronholm__exceptiongroup.0b4f4937", + "agronholm/exceptiongroup" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "semantic_nonoverlap_established": false, + "source_commit": "a869eb3e2155743e2b3e307fa943dea76294c5d1", + "source_dataset": "SWE-bench/SWE-smith-py", + "source_head_commit": "2239deee3315c003206967c18418544aad587514", + "source_kind": "mutation", + "source_repo": "swesmith/agronholm__exceptiongroup.0b4f4937", + "source_revision": "77cab9055d42ab4a5c25c89a8f937096db13558e", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g", + "task_sha256": "9c22d7b44fb4074d808ba1dd3e0d032db429438eefa6f5c95538835e55d84f61", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "agronholm/exceptiongroup", + "usage": "quarantine_only" + }, + "task_bundle_license": { + "reviewed": true, + "sha256": "18afda407941c9d3c65ff530bedd3bc93f3a13d9504ee5728e959fb43ffce808", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/datasets/SWE-bench/SWE-smith-py/raw/77cab9055d42ab4a5c25c89a8f937096db13558e/README.md" + }, + "training_admissible": false, + "trusted_tests_sha256": "1a8481adc545af13be5f1f3f791b88d9b11668589fbbd44bc619ce8ed322bb55" +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/provided-gold.diff b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/provided-gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..e5ff4fe9bd06d65b2ac06e5420fb81d332d9c9bb --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/provided-gold.diff @@ -0,0 +1,15 @@ +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 4c59356f13323c842c5c03f2e7790a6c0c7bb178..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -420,8 +420,8 @@ + ) -> List[str]: + return list( + PatchedTracebackException( +- type(__exc), __exc, __exc.__traceback__, limit=limit, compact=False +- ).format(chain=not chain) ++ type(__exc), __exc, __exc.__traceback__, limit=limit, compact=True ++ ).format(chain=chain) + ) + + diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/solution/solve.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a6c5638137ed101b60b43014010a721c70db3104 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/solution/solve.sh @@ -0,0 +1,21 @@ +#!/bin/bash +set -Eeuo pipefail +cd /testbed/repo +cat > /tmp/openenv-reference.diff <<'OPENENV_REFERENCE' +diff --git a/src/exceptiongroup/_formatting.py b/src/exceptiongroup/_formatting.py +index 4c59356f13323c842c5c03f2e7790a6c0c7bb178..4c52d77bcaaa811202bfd5f20e16487ed6cd2cf8 100644 +--- a/src/exceptiongroup/_formatting.py ++++ b/src/exceptiongroup/_formatting.py +@@ -420,8 +420,8 @@ + ) -> List[str]: + return list( + PatchedTracebackException( +- type(__exc), __exc, __exc.__traceback__, limit=limit, compact=False +- ).format(chain=not chain) ++ type(__exc), __exc, __exc.__traceback__, limit=limit, compact=True ++ ).format(chain=chain) + ) + + +OPENENV_REFERENCE +/usr/bin/git -c core.hooksPath=/dev/null -c core.fsmonitor=false apply --whitespace=nowarn /tmp/openenv-reference.diff diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/task.toml b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dde2b3eb9a6a195e7fba213f68d7bd8a274da05e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/task.toml @@ -0,0 +1,24 @@ +version = "1.0" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 900.0 + +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:73bee9360d40e93b0be64d1113ca3f701799a7de3b7b62fa1f7a4fca5c6a2823" +build_timeout_sec = 600.0 +cpus = 2 +memory_mb = 8192 +storage_mb = 16384 + +[metadata] +author_name = "SWE-smith source adapter" +category = "bugfix" +tags = ["swe", "python", "mutation-repair"] + +[environment.env] +# The image's PATH with the testbed env first: the project and pytest are installed there, and the agent's +# non-interactive shells never run `conda activate` +PATH = "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/check_pytest.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/check_pytest.py new file mode 100644 index 0000000000000000000000000000000000000000..7abfdc5972f57ca7f0cecbbeeb373414670f780e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/check_pytest.py @@ -0,0 +1,177 @@ +"""Preserve confirmed requested assertion failures; keep positive checks strict.""" + +import argparse +import hashlib +import json +import re +import xml.etree.ElementTree as ET +from pathlib import Path + +GROUPS = ("pass-to-pass", "fail-to-pass") + + +def split_nodeid(target): + prefix, bracket, parameter = target.partition("[") + parts = prefix.split("::") + if bracket: + parts[-1] += bracket + parameter + return parts + + +def matches(case, target): + parts = split_nodeid(target) + module = parts[0].removesuffix(".py").replace("/", ".") + classname, name = case.get("classname", ""), case.get("name", "") + if not (classname == module or classname.startswith(module + ".")): + return False + selector = parts[-1] if len(parts) > 1 else "" + classes = parts[1:-1] + if classes and classname != module + "." + ".".join(classes): + return False + return ( + not selector + or name == selector + or ("[" not in selector and name.startswith(selector + "[")) + ) + + +def capture_panels(root): + panels, digests = {}, {} + for group in GROUPS: + path = Path(root) / (group + ".xml") + if not path.exists(): + panels[group] = None + continue + with path.open("rb") as stream: + raw = stream.read(4 * 1024**2 + 1) + if not 0 < len(raw) <= 4 * 1024**2 or re.search( + rb" 20000: + raise ValueError("Too many pytest cases") + identities = [(case.get("classname"), case.get("name")) for case in cases] + if len(identities) != len(set(identities)): + raise ValueError("Duplicate pytest case evidence") + panels[group] = cases + digests[group] = hashlib.sha256(raw).hexdigest() + return panels, digests + + +def strict_assess(panels, expected, native_exit): + """The original positive-approval conditions, applied to captured cases.""" + all_cases, actual_failure = [], False + for group in GROUPS: + cases = panels[group] + if cases is None: + if actual_failure: + continue + raise ValueError("Missing preceding pytest panel") + if actual_failure: + raise ValueError( + "Pytest evidence continued after the native stop-on-failure" + ) + targets = expected[group] + if any(not any(matches(case, target) for target in targets) for case in cases): + raise ValueError("Unexpected pytest case") + all_cases.extend(cases) + failures = [case for case in cases if case.find("failure") is not None] + if any( + case.find("error") is not None or case.find("skipped") is not None + for case in cases + ): + raise ValueError("Pytest collection/error/skip is not a completed panel") + actual_failure = actual_failure or bool(failures) + if not failures and any( + not any(matches(case, target) for case in cases) for target in targets + ): + raise ValueError("Declared pytest target never ran") + if actual_failure: + if native_exit == 0: + raise ValueError("Native verifier exit disagrees with pytest failure") + return {"reward": 0, "valid_test_failure": True, "cases": len(all_cases)} + if native_exit != 0: + raise ValueError("Setup or native verifier failed without a real test failure") + if any(panels[group] is None for group in GROUPS): + raise ValueError("Missing completed pytest panel") + return {"reward": 1, "valid_test_failure": False, "cases": len(all_cases)} + + +def assess(root, expected, native_exit): + if type(native_exit) is not int: + raise ValueError("Native verifier exit must be an integer") + if not isinstance(expected, dict) or any( + not isinstance(expected.get(group), list) + or not expected[group] + or any(not isinstance(target, str) or not target for target in expected[group]) + for group in GROUPS + ): + raise ValueError("Complete exact native pytest targets required") + panels, digests = capture_panels(root) + counts = { + "cases": 0, + "matched_failures": 0, + "unexpected_cases": 0, + "unmatched_failures": 0, + "skipped_cases": 0, + "error_cases": 0, + "missing_panels": 0, + "missing_targets": 0, + } + for group in GROUPS: + cases = panels[group] + if cases is None: + counts["missing_panels"] += 1 + counts["missing_targets"] += len(expected[group]) + continue + counts["cases"] += len(cases) + for case in cases: + requested = any(matches(case, target) for target in expected[group]) + failure = case.find("failure") is not None + counts["matched_failures"] += int(requested and failure) + counts["unmatched_failures"] += int(not requested and failure) + counts["unexpected_cases"] += int(not requested) + counts["skipped_cases"] += int(case.find("skipped") is not None) + counts["error_cases"] += int(case.find("error") is not None) + counts["missing_targets"] += sum( + not any(matches(case, target) for case in cases) + for target in expected[group] + ) + if counts["matched_failures"]: + if native_exit == 0: + raise ValueError( + "Native verifier exit disagrees with requested pytest failure" + ) + return { + "reward": 0, + "valid_test_failure": True, + "cases": counts["cases"], + "diagnostic_counts": counts, + "panel_sha256": digests, + "decision": "confirmed_requested_failure_precedence", + } + result = strict_assess(panels, expected, native_exit) + result.update(diagnostic_counts=counts, panel_sha256=digests) + return result + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--root", required=True) + parser.add_argument("--expected", required=True) + parser.add_argument("--native-exit", type=int, required=True) + args = parser.parse_args() + result = assess( + args.root, json.loads(Path(args.expected).read_bytes()), args.native_exit + ) + reward = Path(args.root) / "reward.txt" + if reward.read_text().strip() != str(result["reward"]): + raise ValueError("Native raw reward disagrees with pytest evidence") + (Path(args.root) / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/expected-panels.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/expected-panels.json new file mode 100644 index 0000000000000000000000000000000000000000..d61d9b336313562108a3798048c48d6b132b0acf --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/expected-panels.json @@ -0,0 +1,95 @@ +{ + "fail-to-pass": [ + "tests/test_formatting.py::test_format_nested" + ], + "pass-to-pass": [ + "tests/test_catch.py::test_bad_arg", + "tests/test_catch.py::test_bad_handler", + "tests/test_catch.py::test_catch_exceptiongroup[naked_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[naked_group]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_basegroup]", + "tests/test_catch.py::test_catch_exceptiongroup[iterable_group]", + "tests/test_catch.py::test_catch_ungrouped", + "tests/test_catch.py::test_catch_group", + "tests/test_catch.py::test_catch_nested_group", + "tests/test_catch.py::test_catch_no_match", + "tests/test_catch.py::test_catch_single_no_match", + "tests/test_catch.py::test_catch_full_match", + "tests/test_catch.py::test_catch_handler_raises", + "tests/test_catch.py::test_bare_raise_in_handler", + "tests/test_catch.py::test_catch_subclass", + "tests/test_catch.py::test_async_handler", + "tests/test_catch.py::test_bare_reraise_from_naked_exception", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_is_generic_type", + "tests/test_exceptions.py::TestExceptionGroupTypeHierarchy::test_exception_group_types", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_excs_sequence", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__bad_message", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__nested_non_exceptions", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_few_args", + "tests/test_exceptions.py::BadConstructorArgs::test_bad_EG_construction__too_many_args", + "tests/test_exceptions.py::InstanceCreation::test_BEG_and_E_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_BaseException__creates_BEG", + "tests/test_exceptions.py::InstanceCreation::test_BEG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_does_not_wrap_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_subclass_wraps_non_base_exceptions", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_BaseException__raises_TypeError", + "tests/test_exceptions.py::InstanceCreation::test_EG_wraps_Exceptions__creates_EG", + "tests/test_exceptions.py::ExceptionGroupFields::test_basics_ExceptionGroup_fields", + "tests/test_exceptions.py::ExceptionGroupFields::test_derive_doesn_copy_notes", + "tests/test_exceptions.py::ExceptionGroupFields::test_fields_are_readonly", + "tests/test_exceptions.py::ExceptionGroupFields::test_notes_is_list_of_strings_if_it_exists", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_by_type__passthrough", + "tests/test_exceptions.py::ExceptionGroupSubgroupTests::test_basics_subgroup_split__bad_arg_type", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_predicate__passthrough", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__no_match", + "tests/test_exceptions.py::ExceptionGroupSplitTests::test_basics_split_by_type__passthrough", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_split", + "tests/test_exceptions.py::DeepRecursionInSplitAndSubgroup::test_deep_subgroup", + "tests/test_exceptions.py::LeafGeneratorTest::test_leaf_generator", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_iteration_full_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_exception_group_tracebacks", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_chaining", + "tests/test_exceptions.py::NestedExceptionGroupBasicsTest::test_nested_group_matches_template", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_BaseExceptionGroup", + "tests/test_exceptions.py::NestedExceptionGroupSplitTest::test_split_by_type", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_BaseExceptionGroup_subclass_no_derive_new_override", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_derive_and_new_overrides", + "tests/test_exceptions.py::NestedExceptionGroupSubclassSplitTest::test_split_ExceptionGroup_subclass_no_derive_no_new_override", + "tests/test_exceptions.py::test_repr", + "tests/test_formatting.py::test_exceptionhook", + "tests/test_formatting.py::test_exceptiongroup_as_cause", + "tests/test_formatting.py::test_exceptiongroup_loop", + "tests/test_formatting.py::test_exceptionhook_format_exception_only", + "tests/test_formatting.py::test_formatting_syntax_error", + "tests/test_formatting.py::test_format_exception[patched-newstyle]", + "tests/test_formatting.py::test_format_exception[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[patched-oldstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-newstyle]", + "tests/test_formatting.py::test_format_exception_only[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exception[patched-newstyle]", + "tests/test_formatting.py::test_print_exception[patched-oldstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-newstyle]", + "tests/test_formatting.py::test_print_exception[unpatched-oldstyle]", + "tests/test_formatting.py::test_print_exc[patched]", + "tests/test_formatting.py::test_print_exc[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions[patched]", + "tests/test_formatting.py::test_nameerror_suggestions[unpatched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[patched]", + "tests/test_formatting.py::test_nameerror_suggestions_in_group[unpatched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[patched]", + "tests/test_formatting.py::test_bug_suggestions_attributeerror_no_obj[unpatched]", + "tests/test_formatting.py::test_works_around_httperror_bug", + "tests/test_suppress.py::test_suppress_exception" + ] +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/grade.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..e3b37293830e51a5c5833c93c4705e1ed9364257 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/grade.py @@ -0,0 +1,128 @@ +"""Trusted private pytest panel runner. Installed only in a fresh grader Job.""" + +import hashlib +import importlib.util +import json +import os +import shutil +import stat +import subprocess +from pathlib import Path, PurePosixPath + + +def sha(raw): + return hashlib.sha256(raw).hexdigest() + + +def safe(value): + path = PurePosixPath(value) + if ( + path.is_absolute() + or path.as_posix() != value + or not path.parts + or any(part in {".", "..", ".git"} for part in path.parts) + ): + raise ValueError("Unsafe trusted test path") + return path + + +def restore(worktree, private, manifest): + worktree, private = Path(worktree), Path(private) + captured = {} + for name, expected in manifest["files"].items(): + path = private / safe(name) + info = path.lstat() + raw = path.read_bytes() if stat.S_ISREG(info.st_mode) else b"" + if ( + not stat.S_ISREG(info.st_mode) + or len(raw) != expected["bytes"] + or sha(raw) != expected["sha256"] + or stat.S_IMODE(info.st_mode) != expected["mode"] + ): + raise ValueError("Trusted private test bytes or modes drifted") + captured[name] = (raw, expected["mode"]) + # Capture and verify every private byte before changing the submitted tree. + for name in manifest["directory_roots"]: + destination = worktree / safe(name) + if destination.is_symlink(): + raise ValueError("Submitted test directory is a symlink") + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.exists(): + if not destination.is_dir(): + raise ValueError("Submitted test directory is not a directory") + shutil.rmtree(destination) + for name, (raw, mode) in captured.items(): + destination = worktree / safe(name) + for parent in destination.parents: + if parent == worktree: + break + if parent.is_symlink(): + raise ValueError("Submitted test parent is a symlink") + if destination.is_symlink(): + raise ValueError("Submitted trusted file is a symlink") + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(raw) + destination.chmod(mode) + + +def run(worktree, private_root, output, invoke=None): + private_root, output, worktree = Path(private_root), Path(output), Path(worktree) + expected = json.loads((private_root / "expected-panels.json").read_bytes()) + config = json.loads((private_root / "panel-config.json").read_bytes()) + manifest = json.loads((private_root / "trusted-inventory.json").read_bytes()) + restore(worktree, private_root / "trusted", manifest) + output.mkdir(parents=True, exist_ok=True) + for name in ( + "reward.txt", + "pass-to-pass.xml", + "fail-to-pass.xml", + "pytest-evidence.json", + ): + (output / name).unlink(missing_ok=True) + environment = dict(os.environ) + for key in ("PYTEST_ADDOPTS", "PYTEST_DISABLE_PLUGIN_AUTOLOAD", "PYTHONPATH"): + environment.pop(key, None) + commands, native_exit = [], 0 + invoke = invoke or subprocess.run + for group in ("pass-to-pass", "fail-to-pass"): + if ( + not isinstance(expected[group], list) + or not expected[group] + or any( + not isinstance(target, str) or not target for target in expected[group] + ) + ): + raise ValueError("Frozen native pytest selectors are incomplete") + command = [ + *config["official_pytest_argv"], + "--override-ini=addopts=", + "--junitxml=" + str(output / (group + ".xml")), + *expected[group], + ] + result = invoke(command, cwd=worktree, env=environment, check=False) + native_exit = result.returncode + commands.append({"group": group, "argv": command, "exit_code": native_exit}) + if native_exit != 0: + break + (output / "pytest-commands.json").write_text( + json.dumps(commands, sort_keys=True) + "\n" + ) + spec = importlib.util.spec_from_file_location( + "trusted_pytest_result", private_root / "check_pytest.py" + ) + checker = importlib.util.module_from_spec(spec) + spec.loader.exec_module(checker) + result = checker.assess(output, expected, native_exit) + (output / "reward.txt").write_text(str(result["reward"]) + "\n") + (output / "pytest-evidence.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + return result + + +if __name__ == "__main__": + run("/testbed/repo", "/tests", "/logs/verifier") diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/panel-config.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/panel-config.json new file mode 100644 index 0000000000000000000000000000000000000000..529f0ee981c9f5bbc61dfac82e8540b39168d26d --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/panel-config.json @@ -0,0 +1,26 @@ +{ + "dependency_installation_pinned": false, + "official_install_cmds": [ + "python -m pip install -e ." + ], + "official_pytest_argv": [ + "pytest", + "--disable-warnings", + "--color=no", + "--tb=no", + "--verbose" + ], + "official_test_command": "source /opt/miniconda3/bin/activate; conda activate testbed; pytest --disable-warnings --color=no --tb=no --verbose", + "operator_test_runner_prerequisites": [ + "python -m pip install pytest==8.4.2" + ], + "operator_test_runner_reason": "The official profile invokes pytest, but the common tools runtime does not provide it; pinned separately from source-native project requirements.", + "panel_normalization": "Override project addopts only to execute the exact frozen native panels; add JUnit output, preserve official pytest options and all selectors.", + "python_version": "3.10", + "source_bound_test_dependency_cmds": [ + "python -m pip install -e '.[test]'" + ], + "test_dependency_source_sha256": { + "pyproject.toml": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/test.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81b6d0620f05dbd3b54b4e7ea5de04ce3f8a98e2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -Eeuo pipefail +source /opt/miniconda3/bin/activate +conda activate testbed +cd /testbed/repo +exec python -I /tests/grade.py diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted-inventory.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted-inventory.json new file mode 100644 index 0000000000000000000000000000000000000000..875771139b00a76fd983c42b126a02a3f0aa2f61 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted-inventory.json @@ -0,0 +1,62 @@ +{ + "directory_roots": [ + "tests" + ], + "files": { + "pyproject.toml": { + "bytes": 2630, + "mode": 420, + "sha256": "e1e623a132b248fa412f8ce5d4a00385eef56063371bdc5d02d678ef3cb2abd5" + }, + "tests/__init__.py": { + "bytes": 0, + "mode": 420, + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + }, + "tests/apport_excepthook.py": { + "bytes": 466, + "mode": 420, + "sha256": "5b5a85531a20839ff1c624a2b5a8eb2d00b41e5a5c467b037daa9f23acbb126d" + }, + "tests/check_types.py": { + "bytes": 1025, + "mode": 420, + "sha256": "07bc5f001f4194d6910999aa5c76c5d2e99a3274fa970f77015c0ed7cebf5fea" + }, + "tests/conftest.py": { + "bytes": 84, + "mode": 420, + "sha256": "10fde0caa2257622444f0452ba321c9a34349d7d50dad6291ab189ea31033381" + }, + "tests/test_apport_monkeypatching.py": { + "bytes": 1925, + "mode": 420, + "sha256": "50bddad2c699f04e60f757d00b4071bde931d8583cbdd39a0b24f29cb174f138" + }, + "tests/test_catch.py": { + "bytes": 7163, + "mode": 420, + "sha256": "9e19d73b5eb2796eb2bacc1cae633f63f85b6a0179fd80645b2e26340ae53f80" + }, + "tests/test_catch_py311.py": { + "bytes": 5958, + "mode": 420, + "sha256": "bdcee13b4edcef13bdf5a8c8ea1ff19480267fc9c2cfd6493b85b84c1c03325e" + }, + "tests/test_exceptions.py": { + "bytes": 31247, + "mode": 420, + "sha256": "254cc73bddbd8e9903d1fe1b0403f3b7eb5af337acd16557ed445ad0ee72f747" + }, + "tests/test_formatting.py": { + "bytes": 19274, + "mode": 420, + "sha256": "d1d4252253b81ca7bc2f5a00605e9ceeb82b4d3348eccd9331b0c2251a07da7b" + }, + "tests/test_suppress.py": { + "bytes": 442, + "mode": 420, + "sha256": "d166b2e9aac0d9983afe8894aa10904c8b57b7977100df0cb2b0799d07f309fc" + } + } +} diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/pyproject.toml b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..8416650b069c21c310861168d9a2605e00a6240e --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/pyproject.toml @@ -0,0 +1,111 @@ +[build-system] +requires = ["flit_scm"] +build-backend = "flit_scm:buildapi" + +[project] +name = "exceptiongroup" +description = "Backport of PEP 654 (exception groups)" +readme = "README.rst" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Typing :: Typed" +] +authors = [{name = "Alex Grönholm", email = "alex.gronholm@nextday.fi"}] +license = {file = "LICENSE"} +requires-python = ">=3.7" +dynamic = ["version"] + +[project.urls] +Changelog = "https://github.com/agronholm/exceptiongroup/blob/main/CHANGES.rst" +"Source code" = "https://github.com/agronholm/exceptiongroup" +"Issue Tracker" = "https://github.com/agronholm/exceptiongroup/issues" + +[project.optional-dependencies] +test = [ + "pytest >= 6" +] + +[tool.flit.sdist] +include = [ + "CHANGES.rst", + "tests", +] +exclude = [ + ".github/*", + ".gitignore", + ".pre-commit-config.yaml" +] + +[tool.setuptools_scm] +version_scheme = "post-release" +local_scheme = "dirty-tag" +write_to = "src/exceptiongroup/_version.py" + +[tool.ruff.lint] +extend-select = [ + "I", # isort + "ISC", # flake8-implicit-str-concat + "PGH", # pygrep-hooks + "RUF100", # unused noqa (yesqa) + "UP", # pyupgrade + "W", # pycodestyle warnings +] + +[tool.ruff.lint.pyupgrade] +# Preserve types, even if a file imports `from __future__ import annotations`. +keep-runtime-typing = true + +[tool.ruff.lint.isort] +known-first-party = ["exceptiongroup"] + +[tool.pytest.ini_options] +addopts = "-rsx --tb=short --strict-config --strict-markers" +testpaths = ["tests"] + +[tool.coverage.run] +source = ["exceptiongroup"] +relative_files = true + +[tool.coverage.report] +exclude_also = [ + "if TYPE_CHECKING:", + "@overload", +] + +[tool.pyright] +# for type tests, the code itself isn't type checked in CI +reportUnnecessaryTypeIgnoreComment = true + +[tool.mypy] +# for type tests, the code itself isn't type checked in CI +warn_unused_ignores = true + +[tool.tox] +legacy_tox_ini = """ +[tox] +envlist = py37, py38, py39, py310, py311, py312, py313, pypy3 +labels = + typing = py{310,311,312}-typing +skip_missing_interpreters = true +minversion = 4.0 + +[testenv] +extras = test +commands = python -m pytest {posargs} +package = editable +usedevelop = true + +[testenv:{py37-,py38-,py39-,py310-,py311-,py312-,}typing] +deps = + pyright + mypy +commands = + pyright --verifytypes exceptiongroup + pyright tests/check_types.py + mypy tests/check_types.py +usedevelop = true +""" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/__init__.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/apport_excepthook.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/apport_excepthook.py new file mode 100644 index 0000000000000000000000000000000000000000..1e4a8f30deeac30ae534247ce59dfa6a4ee6c5fa --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/apport_excepthook.py @@ -0,0 +1,13 @@ +# The apport_python_hook package is only installed as part of Ubuntu's system +# python, and not available in venvs. So before we can import it we have to +# make sure it's on sys.path. +import sys + +sys.path.append("/usr/lib/python3/dist-packages") +import apport_python_hook # unsorted import + +apport_python_hook.install() + +from exceptiongroup import ExceptionGroup # noqa: E402 # unsorted import + +raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/check_types.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/check_types.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a102d5d8ab278e6bbb45fd9572d6ea41a723b2 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/check_types.py @@ -0,0 +1,36 @@ +from typing_extensions import assert_type + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch, suppress + +# issue 117 +a = BaseExceptionGroup("", (KeyboardInterrupt(),)) +assert_type(a, BaseExceptionGroup[KeyboardInterrupt]) +b = BaseExceptionGroup("", (ValueError(),)) +assert_type(b, BaseExceptionGroup[ValueError]) +c = ExceptionGroup("", (ValueError(),)) +assert_type(c, ExceptionGroup[ValueError]) + +# expected type error when passing a BaseException to ExceptionGroup +ExceptionGroup("", (KeyboardInterrupt(),)) # type: ignore[type-var] + + +# code snippets from the README + + +def value_key_err_handler(excgroup: BaseExceptionGroup) -> None: + for exc in excgroup.exceptions: + print("Caught exception:", type(exc)) + + +def runtime_err_handler(exc: BaseExceptionGroup) -> None: + print("Caught runtime error") + + +with catch( + {(ValueError, KeyError): value_key_err_handler, RuntimeError: runtime_err_handler} +): + ... + + +with suppress(RuntimeError): + raise ExceptionGroup("", [RuntimeError("boo")]) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/conftest.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..aeca72d3b5e6f178a10d7913fb593b45b92fd342 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/conftest.py @@ -0,0 +1,4 @@ +import sys + +if sys.version_info < (3, 11): + collect_ignore_glob = ["*_py311.py"] diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_apport_monkeypatching.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_apport_monkeypatching.py new file mode 100644 index 0000000000000000000000000000000000000000..998554fde690d23fe93e3f879d14b816323a7d25 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_apport_monkeypatching.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +import exceptiongroup + + +def run_script(name: str) -> subprocess.CompletedProcess[bytes]: + exceptiongroup_path = Path(exceptiongroup.__file__).parent.parent + script_path = Path(__file__).parent / name + + env = dict(os.environ) + print("parent PYTHONPATH:", env.get("PYTHONPATH")) + if "PYTHONPATH" in env: # pragma: no cover + pp = env["PYTHONPATH"].split(os.pathsep) + else: + pp = [] + + pp.insert(0, str(exceptiongroup_path)) + pp.insert(0, str(script_path.parent)) + env["PYTHONPATH"] = os.pathsep.join(pp) + print("subprocess PYTHONPATH:", env.get("PYTHONPATH")) + + cmd = [sys.executable, "-u", str(script_path)] + print("running:", cmd) + completed = subprocess.run( + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT + ) + print("process output:") + print(completed.stdout.decode("utf-8")) + return completed + + +@pytest.mark.skipif( + sys.version_info > (3, 11), + reason="No patching is done on Python >= 3.11", +) +@pytest.mark.skipif( + not Path("/usr/lib/python3/dist-packages/apport_python_hook.py").exists(), + reason="need Ubuntu with python3-apport installed", +) +def test_apport_excepthook_monkeypatch_interaction(): + completed = run_script("apport_excepthook.py") + stdout = completed.stdout.decode("utf-8") + file = Path(__file__).parent / "apport_excepthook.py" + assert stdout == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{file}", line 13, in + | raise ExceptionGroup("msg1", [KeyError("msg2"), ValueError("msg3")]) + | exceptiongroup.ExceptionGroup: msg1 (2 sub-exceptions) + +-+---------------- 1 ---------------- + | KeyError: 'msg2' + +---------------- 2 ---------------- + | ValueError: msg3 + +------------------------------------ +""" + ) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_catch.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_catch.py new file mode 100644 index 0000000000000000000000000000000000000000..1da749e23c6ed9b75f6f1e2c2fb27ac1f3048207 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_catch.py @@ -0,0 +1,222 @@ +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup, catch + + +def test_bad_arg(): + with pytest.raises(TypeError, match="the argument must be a mapping"): + with catch(1): + pass + + +def test_bad_handler(): + with pytest.raises(TypeError, match="handlers must be callable"): + with catch({RuntimeError: None}): + pass + + +@pytest.mark.parametrize( + "exc_type", + [ + pytest.param(BaseExceptionGroup, id="naked_basegroup"), + pytest.param(ExceptionGroup, id="naked_group"), + pytest.param((ValueError, BaseExceptionGroup), id="iterable_basegroup"), + pytest.param((ValueError, ExceptionGroup), id="iterable_group"), + ], +) +def test_catch_exceptiongroup(exc_type): + with pytest.raises(TypeError, match="catching ExceptionGroup with catch"): + with catch({exc_type: (lambda e: True)}): + pass + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + with catch( + { + (ValueError, TypeError): value_type_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise exc + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + with catch( + { + (ValueError, RuntimeError): value_runtime_errors.append, + ZeroDivisionError: zero_division_errors.append, + } + ): + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except ExceptionGroup as exc: + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ZeroDivisionError + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + with catch({(ValueError, RuntimeError): (lambda e: None)}): + raise ExceptionGroup("booboo", [ValueError()]) + + +def test_catch_handler_raises(): + def handler(exc): + raise RuntimeError("new") + + with pytest.raises(RuntimeError, match="new") as exc: + with catch({(ValueError, ValueError): handler}): + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_bare_raise_in_handler(): + """Test that a bare "raise" "middle" ecxeption group gets discarded.""" + + def handler(exc): + raise + + with pytest.raises(ExceptionGroup) as excgrp: + with catch({(ValueError,): handler, (RuntimeError,): lambda eg: None}): + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + + assert len(excgrp.value.exceptions) == 2 + assert all(isinstance(exc, ValueError) for exc in excgrp.value.exceptions) + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_catch_subclass(): + lookup_errors = [] + with catch({LookupError: lookup_errors.append}): + raise KeyError("foo") + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_async_handler(request): + async def handler(eg): + pass + + def delegate(eg): + coro = handler(eg) + request.addfinalizer(coro.close) + return coro + + with pytest.raises(TypeError, match="Exception handler must be a sync function."): + with catch({TypeError: delegate}): + raise ExceptionGroup("message", [TypeError("uh-oh")]) + + +def test_bare_reraise_from_naked_exception(): + def handler(eg): + raise + + with pytest.raises(ExceptionGroup) as excgrp, catch({Exception: handler}): + raise KeyError("foo") + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_catch_py311.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_catch_py311.py new file mode 100644 index 0000000000000000000000000000000000000000..2f12ac32a28361a36d7e8c1312e3b0fccb6ce494 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_catch_py311.py @@ -0,0 +1,190 @@ +import sys + +import pytest + +from exceptiongroup import ExceptionGroup + + +def test_catch_ungrouped(): + value_type_errors = [] + zero_division_errors = [] + for exc in [ValueError("foo"), TypeError("bar"), ZeroDivisionError()]: + try: + raise exc + except* (ValueError, TypeError) as e: + value_type_errors.append(e) + except* ZeroDivisionError as e: + zero_division_errors.append(e) + + assert len(value_type_errors) == 2 + + assert isinstance(value_type_errors[0], ExceptionGroup) + assert len(value_type_errors[0].exceptions) == 1 + assert isinstance(value_type_errors[0].exceptions[0], ValueError) + + assert isinstance(value_type_errors[1], ExceptionGroup) + assert len(value_type_errors[1].exceptions) == 1 + assert isinstance(value_type_errors[1].exceptions[0], TypeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ZeroDivisionError) + assert len(zero_division_errors[0].exceptions) == 1 + + +def test_catch_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + raise ExceptionGroup( + "booboo", + [ + ValueError("foo"), + ValueError("bar"), + RuntimeError("bar"), + ZeroDivisionError(), + ], + ) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + assert isinstance(value_runtime_errors[0], ExceptionGroup) + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ValueError) + assert isinstance(exceptions[2], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + exceptions = zero_division_errors[0].exceptions + assert isinstance(exceptions[0], ZeroDivisionError) + + +def test_catch_nested_group(): + value_runtime_errors = [] + zero_division_errors = [] + try: + nested_group = ExceptionGroup( + "nested", [RuntimeError("bar"), ZeroDivisionError()] + ) + raise ExceptionGroup("booboo", [ValueError("foo"), nested_group]) + except* (ValueError, RuntimeError) as exc: + value_runtime_errors.append(exc) + except* ZeroDivisionError as exc: + zero_division_errors.append(exc) + + assert len(value_runtime_errors) == 1 + exceptions = value_runtime_errors[0].exceptions + assert isinstance(exceptions[0], ValueError) + assert isinstance(exceptions[1], ExceptionGroup) + assert isinstance(exceptions[1].exceptions[0], RuntimeError) + + assert len(zero_division_errors) == 1 + assert isinstance(zero_division_errors[0], ExceptionGroup) + assert isinstance(zero_division_errors[0].exceptions[0], ExceptionGroup) + assert isinstance( + zero_division_errors[0].exceptions[0].exceptions[0], ZeroDivisionError + ) + + +def test_catch_no_match(): + try: + try: + group = ExceptionGroup("booboo", [ZeroDivisionError()]) + raise group + except* (ValueError, RuntimeError): + pass + except ExceptionGroup as exc: + assert isinstance(exc.exceptions[0], ZeroDivisionError) + assert exc is not group + else: + pytest.fail("Did not raise an ExceptionGroup") + + +def test_catch_single_no_match(): + try: + try: + raise ZeroDivisionError + except* (ValueError, RuntimeError): + pass + except ZeroDivisionError: + pass + else: + pytest.fail("Did not raise an ZeroDivisionError") + + +def test_catch_full_match(): + try: + raise ExceptionGroup("booboo", [ValueError()]) + except* (ValueError, RuntimeError): + pass + + +@pytest.mark.skipif( + sys.version_info < (3, 11, 4), + reason="Behavior was changed in 3.11.4", +) +def test_catch_handler_raises(): + with pytest.raises(RuntimeError, match="new") as exc: + try: + excgrp = ExceptionGroup("booboo", [ValueError("bar")]) + raise excgrp + except* ValueError: + raise RuntimeError("new") + + context = exc.value.__context__ + assert isinstance(context, ExceptionGroup) + assert str(context) == "booboo (1 sub-exception)" + assert len(context.exceptions) == 1 + assert isinstance(context.exceptions[0], ValueError) + assert exc.value.__cause__ is None + + +def test_catch_subclass(): + lookup_errors = [] + try: + raise KeyError("foo") + except* LookupError as e: + lookup_errors.append(e) + + assert len(lookup_errors) == 1 + assert isinstance(lookup_errors[0], ExceptionGroup) + exceptions = lookup_errors[0].exceptions + assert isinstance(exceptions[0], KeyError) + + +def test_bare_raise_in_handler(): + """Test that the "middle" ecxeption group gets discarded.""" + with pytest.raises(ExceptionGroup) as excgrp: + try: + try: + first_exc = RuntimeError("first") + raise first_exc + except RuntimeError as exc: + middle_exc = ExceptionGroup( + "bad", [ValueError(), ValueError(), TypeError()] + ) + raise middle_exc from exc + except* ValueError: + raise + except* TypeError: + pass + + assert excgrp.value is not middle_exc + assert excgrp.value.__cause__ is first_exc + assert excgrp.value.__context__ is first_exc + + +def test_bare_reraise_from_naked_exception(): + with pytest.raises(ExceptionGroup) as excgrp: + try: + raise KeyError("foo") + except* KeyError: + raise + + assert len(excgrp.value.exceptions) == 1 + assert isinstance(excgrp.value.exceptions[0], KeyError) + assert str(excgrp.value.exceptions[0]) == "'foo'" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_exceptions.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f77511ab61e277226c225bee1fc4bae395d1f339 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_exceptions.py @@ -0,0 +1,845 @@ +# Copied from the standard library +import collections.abc +import sys +import unittest + +import pytest + +from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +class TestExceptionGroupTypeHierarchy(unittest.TestCase): + def test_exception_group_types(self): + self.assertTrue(issubclass(ExceptionGroup, Exception)) + self.assertTrue(issubclass(ExceptionGroup, BaseExceptionGroup)) + self.assertTrue(issubclass(BaseExceptionGroup, BaseException)) + + def test_exception_group_is_generic_type(self): + E = OSError + self.assertEqual(ExceptionGroup[E].__origin__, ExceptionGroup) + self.assertEqual(BaseExceptionGroup[E].__origin__, BaseExceptionGroup) + + +class BadConstructorArgs(unittest.TestCase): + def test_bad_EG_construction__too_few_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(1 given\)" + ) + else: + MSG = ( + r"__new__\(\) missing 1 required positional argument: " + r"'_ExceptionGroup__exceptions'" + ) + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("no errors") + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup([ValueError("no msg")]) + + def test_bad_EG_construction__too_many_args(self): + if sys.version_info >= (3, 11): + MSG = ( + r"BaseExceptionGroup.__new__\(\) takes exactly 2 arguments \(3 given\)" + ) + else: + MSG = r"__new__\(\) takes 3 positional arguments but 4 were given" + + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError("too")], [TypeError("many")]) + + def test_bad_EG_construction__bad_message(self): + MSG = "argument 1 must be str, not " + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(ValueError(12), SyntaxError("bad syntax")) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup(None, [ValueError(12)]) + + def test_bad_EG_construction__bad_excs_sequence(self): + MSG = r"second argument \(exceptions\) must be a sequence" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("errors not sequence", {ValueError(42)}) + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", None) + + MSG = r"second argument \(exceptions\) must be a non-empty sequence" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("eg", []) + + def test_bad_EG_construction__nested_non_exceptions(self): + MSG = r"Item [0-9]+ of second argument \(exceptions\) is not an exception" + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("expect instance, not type", [OSError]) + with self.assertRaisesRegex(ValueError, MSG): + ExceptionGroup("bad error", ["not an exception"]) + + +class InstanceCreation(unittest.TestCase): + def test_EG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(ExceptionGroup("eg", excs)), ExceptionGroup) + + def test_BEG_wraps_Exceptions__creates_EG(self): + excs = [ValueError(1), TypeError(2)] + self.assertIs(type(BaseExceptionGroup("beg", excs)), ExceptionGroup) + + def test_EG_wraps_BaseException__raises_TypeError(self): + MSG = "Cannot nest BaseExceptions in an ExceptionGroup" + with self.assertRaisesRegex(TypeError, MSG): + ExceptionGroup("eg", [ValueError(1), KeyboardInterrupt(2)]) + + def test_BEG_wraps_BaseException__creates_BEG(self): + beg = BaseExceptionGroup("beg", [ValueError(1), KeyboardInterrupt(2)]) + self.assertIs(type(beg), BaseExceptionGroup) + + def test_EG_subclass_wraps_non_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + self.assertIs(type(MyEG("eg", [ValueError(12), TypeError(42)])), MyEG) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_EG_subclass_does_not_wrap_base_exceptions(self): + class MyEG(ExceptionGroup): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + @pytest.mark.skipif( + sys.version_info[:3] == (3, 11, 0), + reason="Behavior was made stricter in 3.11.1", + ) + def test_BEG_and_E_subclass_does_not_wrap_base_exceptions(self): + class MyEG(BaseExceptionGroup, ValueError): + pass + + msg = "Cannot nest BaseExceptions in 'MyEG'" + with self.assertRaisesRegex(TypeError, msg): + MyEG("eg", [ValueError(12), KeyboardInterrupt(42)]) + + +def create_simple_eg(): + excs = [] + try: + try: + raise MemoryError("context and cause for ValueError(1)") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + try: + raise OSError("context for TypeError") + except OSError: + raise TypeError(int) + except TypeError as e: + excs.append(e) + + try: + try: + raise ImportError("context for ValueError(2)") + except ImportError: + raise ValueError(2) + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("simple eg", excs) + except ExceptionGroup as e: + return e + + +class ExceptionGroupFields(unittest.TestCase): + def test_basics_ExceptionGroup_fields(self): + eg = create_simple_eg() + + # check msg + self.assertEqual(eg.message, "simple eg") + self.assertEqual(eg.args[0], "simple eg") + + # check cause and context + self.assertIsInstance(eg.exceptions[0], ValueError) + self.assertIsInstance(eg.exceptions[0].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1], TypeError) + self.assertIsNone(eg.exceptions[1].__cause__) + self.assertIsInstance(eg.exceptions[1].__context__, OSError) + self.assertIsInstance(eg.exceptions[2], ValueError) + self.assertIsNone(eg.exceptions[2].__cause__) + self.assertIsInstance(eg.exceptions[2].__context__, ImportError) + + # check tracebacks + line0 = create_simple_eg.__code__.co_firstlineno + tb_linenos = [line0 + 27, [line0 + 6, line0 + 14, line0 + 22]] + self.assertEqual(eg.__traceback__.tb_lineno, tb_linenos[0]) + self.assertIsNone(eg.__traceback__.tb_next) + for i in range(3): + tb = eg.exceptions[i].__traceback__ + self.assertIsNone(tb.tb_next) + self.assertEqual(tb.tb_lineno, tb_linenos[1][i]) + + def test_fields_are_readonly(self): + eg = ExceptionGroup("eg", [TypeError(1), OSError(2)]) + + self.assertEqual(type(eg.exceptions), tuple) + + eg.message + with self.assertRaises(AttributeError): + eg.message = "new msg" + + eg.exceptions + with self.assertRaises(AttributeError): + eg.exceptions = [OSError("xyz")] + + def test_notes_is_list_of_strings_if_it_exists(self): + eg = create_simple_eg() + + note = "This is a happy note for the exception group" + self.assertFalse(hasattr(eg, "__notes__")) + eg.add_note(note) + self.assertEqual(eg.__notes__, [note]) + + def test_derive_doesn_copy_notes(self): + eg = create_simple_eg() + eg.add_note("hello") + assert eg.__notes__ == ["hello"] + eg2 = eg.derive([ValueError()]) + assert not hasattr(eg2, "__notes__") + + +class ExceptionGroupTestBase(unittest.TestCase): + def assertMatchesTemplate(self, exc, exc_type, template): + """Assert that the exception matches the template + + A template describes the shape of exc. If exc is a + leaf exception (i.e., not an exception group) then + template is an exception instance that has the + expected type and args value of exc. If exc is an + exception group, then template is a list of the + templates of its nested exceptions. + """ + if exc_type is not None: + self.assertIs(type(exc), exc_type) + + if isinstance(exc, BaseExceptionGroup): + self.assertIsInstance(template, collections.abc.Sequence) + self.assertEqual(len(exc.exceptions), len(template)) + for e, t in zip(exc.exceptions, template): + self.assertMatchesTemplate(e, None, t) + else: + self.assertIsInstance(template, BaseException) + self.assertEqual(type(exc), type(template)) + self.assertEqual(exc.args, template.args) + + +class ExceptionGroupSubgroupTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_subgroup_split__bad_arg_type(self): + bad_args = [ + "bad arg", + OSError("instance not type"), + [OSError, TypeError], + (OSError, 42), + ] + for arg in bad_args: + with self.assertRaises(TypeError): + self.eg.subgroup(arg) + with self.assertRaises(TypeError): + self.eg.split(arg) + + def test_basics_subgroup_by_type__passthrough(self): + eg = self.eg + # self.assertIs(eg, eg.subgroup(BaseException)) + # self.assertIs(eg, eg.subgroup(Exception)) + self.assertIs(eg, eg.subgroup(BaseExceptionGroup)) + self.assertIs(eg, eg.subgroup(ExceptionGroup)) + + def test_basics_subgroup_by_type__no_match(self): + self.assertIsNone(self.eg.subgroup(OSError)) + + def test_basics_subgroup_by_type__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + with self.subTest(match=match_type): + subeg = eg.subgroup(match_type) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + def test_basics_subgroup_by_predicate__passthrough(self): + self.assertIs(self.eg, self.eg.subgroup(lambda e: True)) + + def test_basics_subgroup_by_predicate__no_match(self): + self.assertIsNone(self.eg.subgroup(lambda e: False)) + + def test_basics_subgroup_by_predicate__match(self): + eg = self.eg + testcases = [ + # (match_type, result_template) + (ValueError, [ValueError(1), ValueError(2)]), + (TypeError, [TypeError(int)]), + ((ValueError, TypeError), self.eg_template), + ] + + for match_type, template in testcases: + subeg = eg.subgroup(lambda e: isinstance(e, match_type)) + self.assertEqual(subeg.message, eg.message) + self.assertMatchesTemplate(subeg, ExceptionGroup, template) + + +class ExceptionGroupSplitTests(ExceptionGroupTestBase): + def setUp(self): + self.eg = create_simple_eg() + self.eg_template = [ValueError(1), TypeError(int), ValueError(2)] + + def test_basics_split_by_type__passthrough(self): + for E in [BaseException, Exception, BaseExceptionGroup, ExceptionGroup]: + match, rest = self.eg.split(E) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_type__no_match(self): + match, rest = self.eg.split(OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_type__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ((OSError, VE), [VE(1), VE(2)], [TE(int)]), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(match_type) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + else: + self.assertIsNone(rest) + + def test_basics_split_by_predicate__passthrough(self): + match, rest = self.eg.split(lambda e: True) + self.assertMatchesTemplate(match, ExceptionGroup, self.eg_template) + self.assertIsNone(rest) + + def test_basics_split_by_predicate__no_match(self): + match, rest = self.eg.split(lambda e: False) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, self.eg_template) + + def test_basics_split_by_predicate__match(self): + eg = self.eg + VE = ValueError + TE = TypeError + testcases = [ + # (matcher, match_template, rest_template) + (VE, [VE(1), VE(2)], [TE(int)]), + (TE, [TE(int)], [VE(1), VE(2)]), + ((VE, TE), self.eg_template, None), + ] + + for match_type, match_template, rest_template in testcases: + match, rest = eg.split(lambda e: isinstance(e, match_type)) + self.assertEqual(match.message, eg.message) + self.assertMatchesTemplate(match, ExceptionGroup, match_template) + if rest_template is not None: + self.assertEqual(rest.message, eg.message) + self.assertMatchesTemplate(rest, ExceptionGroup, rest_template) + + +class DeepRecursionInSplitAndSubgroup(unittest.TestCase): + def make_deep_eg(self): + e = TypeError(1) + for _ in range(10000): + e = ExceptionGroup("eg", [e]) + return e + + def test_deep_split(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.split(TypeError) + + def test_deep_subgroup(self): + e = self.make_deep_eg() + with self.assertRaises(RecursionError): + e.subgroup(TypeError) + + +def leaf_generator(exc, tbs=None): + if tbs is None: + tbs = [] + tbs.append(exc.__traceback__) + if isinstance(exc, BaseExceptionGroup): + for e in exc.exceptions: + yield from leaf_generator(e, tbs) + else: + # exc is a leaf exception and its traceback + # is the concatenation of the traceback + # segments in tbs + yield exc, tbs + tbs.pop() + + +class LeafGeneratorTest(unittest.TestCase): + # The leaf_generator is mentioned in PEP 654 as a suggestion + # on how to iterate over leaf nodes of an EG. Is is also + # used below as a test utility. So we test it here. + + def test_leaf_generator(self): + eg = create_simple_eg() + + self.assertSequenceEqual([e for e, _ in leaf_generator(eg)], eg.exceptions) + + for e, tbs in leaf_generator(eg): + self.assertSequenceEqual(tbs, [eg.__traceback__, e.__traceback__]) + + +def create_nested_eg(): + excs = [] + try: + try: + raise TypeError(bytes) + except TypeError as e: + raise ExceptionGroup("nested", [e]) + except ExceptionGroup as e: + excs.append(e) + + try: + try: + raise MemoryError("out of memory") + except MemoryError as e: + raise ValueError(1) from e + except ValueError as e: + excs.append(e) + + try: + raise ExceptionGroup("root", excs) + except ExceptionGroup as eg: + return eg + + +class NestedExceptionGroupBasicsTest(ExceptionGroupTestBase): + def test_nested_group_matches_template(self): + eg = create_nested_eg() + self.assertMatchesTemplate( + eg, ExceptionGroup, [[TypeError(bytes)], ValueError(1)] + ) + + def test_nested_group_chaining(self): + eg = create_nested_eg() + self.assertIsInstance(eg.exceptions[1].__context__, MemoryError) + self.assertIsInstance(eg.exceptions[1].__cause__, MemoryError) + self.assertIsInstance(eg.exceptions[0].__context__, TypeError) + + def test_nested_exception_group_tracebacks(self): + eg = create_nested_eg() + + line0 = create_nested_eg.__code__.co_firstlineno + for tb, expected in [ + (eg.__traceback__, line0 + 19), + (eg.exceptions[0].__traceback__, line0 + 6), + (eg.exceptions[1].__traceback__, line0 + 14), + (eg.exceptions[0].exceptions[0].__traceback__, line0 + 4), + ]: + self.assertEqual(tb.tb_lineno, expected) + self.assertIsNone(tb.tb_next) + + def test_iteration_full_tracebacks(self): + eg = create_nested_eg() + # check that iteration over leaves + # produces the expected tracebacks + self.assertEqual(len(list(leaf_generator(eg))), 2) + + line0 = create_nested_eg.__code__.co_firstlineno + expected_tbs = [[line0 + 19, line0 + 6, line0 + 4], [line0 + 19, line0 + 14]] + + for i, (_, tbs) in enumerate(leaf_generator(eg)): + self.assertSequenceEqual([tb.tb_lineno for tb in tbs], expected_tbs[i]) + + +class ExceptionGroupSplitTestBase(ExceptionGroupTestBase): + def split_exception_group(self, eg, types): + """Split an EG and do some sanity checks on the result""" + self.assertIsInstance(eg, BaseExceptionGroup) + + match, rest = eg.split(types) + sg = eg.subgroup(types) + + if match is not None: + self.assertIsInstance(match, BaseExceptionGroup) + for e, _ in leaf_generator(match): + self.assertIsInstance(e, types) + + self.assertIsNotNone(sg) + self.assertIsInstance(sg, BaseExceptionGroup) + for e, _ in leaf_generator(sg): + self.assertIsInstance(e, types) + + if rest is not None: + self.assertIsInstance(rest, BaseExceptionGroup) + + def leaves(exc): + return [] if exc is None else [e for e, _ in leaf_generator(exc)] + + # match and subgroup have the same leaves + self.assertSequenceEqual(leaves(match), leaves(sg)) + + match_leaves = leaves(match) + rest_leaves = leaves(rest) + # each leaf exception of eg is in exactly one of match and rest + self.assertEqual(len(leaves(eg)), len(leaves(match)) + len(leaves(rest))) + + for e in leaves(eg): + self.assertNotEqual(match and e in match_leaves, rest and e in rest_leaves) + + # message, cause and context, traceback and note equal to eg + for part in [match, rest, sg]: + if part is not None: + self.assertEqual(eg.message, part.message) + self.assertIs(eg.__cause__, part.__cause__) + self.assertIs(eg.__context__, part.__context__) + self.assertIs(eg.__traceback__, part.__traceback__) + self.assertEqual( + getattr(eg, "__notes__", None), + getattr(part, "__notes__", None), + ) + + def tbs_for_leaf(leaf, eg): + for e, tbs in leaf_generator(eg): + if e is leaf: + return tbs + + def tb_linenos(tbs): + return [tb.tb_lineno for tb in tbs if tb] + + # full tracebacks match + for part in [match, rest, sg]: + for e in leaves(part): + self.assertSequenceEqual( + tb_linenos(tbs_for_leaf(e, eg)), tb_linenos(tbs_for_leaf(e, part)) + ) + + return match, rest + + +class NestedExceptionGroupSplitTest(ExceptionGroupSplitTestBase): + def test_split_by_type(self): + class MyExceptionGroup(ExceptionGroup): + pass + + def raiseVE(v): + raise ValueError(v) + + def raiseTE(t): + raise TypeError(t) + + def nested_group(): + def level1(i): + excs = [] + for f, arg in [(raiseVE, i), (raiseTE, int), (raiseVE, i + 1)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg1", excs) + + def level2(i): + excs = [] + for f, arg in [(level1, i), (level1, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise MyExceptionGroup("msg2", excs) + + def level3(i): + excs = [] + for f, arg in [(level2, i + 1), (raiseVE, i + 2)]: + try: + f(arg) + except Exception as e: + excs.append(e) + raise ExceptionGroup("msg3", excs) + + level3(5) + + try: + nested_group() + except ExceptionGroup as e: + e.add_note(f"the note: {id(e)}") + eg = e + + eg_template = [ + [ + [ValueError(6), TypeError(int), ValueError(7)], + [ValueError(7), TypeError(int), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + valueErrors_template = [ + [ + [ValueError(6), ValueError(7)], + [ValueError(7), ValueError(8)], + ValueError(8), + ], + ValueError(7), + ] + + typeErrors_template = [[[TypeError(int)], [TypeError(int)]]] + + self.assertMatchesTemplate(eg, ExceptionGroup, eg_template) + + # Match Nothing + match, rest = self.split_exception_group(eg, SyntaxError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, ExceptionGroup, eg_template) + + # Match Everything + match, rest = self.split_exception_group(eg, BaseException) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, ExceptionGroup, eg_template) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, valueErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, typeErrors_template) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, (TypeError, SyntaxError)) + self.assertMatchesTemplate(match, ExceptionGroup, typeErrors_template) + self.assertMatchesTemplate(rest, ExceptionGroup, valueErrors_template) + + # Match ExceptionGroup + match, rest = eg.split(ExceptionGroup) + self.assertIs(match, eg) + self.assertIsNone(rest) + + # Match MyExceptionGroup (ExceptionGroup subclass) + match, rest = eg.split(MyExceptionGroup) + self.assertMatchesTemplate(match, ExceptionGroup, [eg_template[0]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [eg_template[1]]) + + def test_split_BaseExceptionGroup(self): + def exc(ex): + try: + raise ex + except BaseException as e: + return e + + try: + raise BaseExceptionGroup( + "beg", [exc(ValueError(1)), exc(KeyboardInterrupt(2))] + ) + except BaseExceptionGroup as e: + beg = e + + # Match Nothing + match, rest = self.split_exception_group(beg, TypeError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(beg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(beg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupts + match, rest = self.split_exception_group(beg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + +class NestedExceptionGroupSubclassSplitTest(ExceptionGroupSplitTestBase): + def test_split_ExceptionGroup_subclass_no_derive_no_new_override(self): + class EG(ExceptionGroup): + pass + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te]) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested]) + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate( + match, ExceptionGroup, [ValueError(1), [TypeError(2)]] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [[TypeError(2)]]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, ExceptionGroup, [[TypeError(2)]]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_BaseExceptionGroup_subclass_no_derive_new_override(self): + class EG(BaseExceptionGroup): + def __new__(cls, message, excs, unused): + # The "unused" arg is here to show that split() doesn't call + # the actual class constructor from the default derive() + # implementation (it would fail on unused arg if so because + # it assumes the BaseExceptionGroup.__new__ signature). + return super().__new__(cls, message, excs) + + try: + raise EG("eg", [ValueError(1), KeyboardInterrupt(2)], "unused") + except EG as e: + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), KeyboardInterrupt(2)]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate( + rest, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, KeyboardInterrupt)) + self.assertMatchesTemplate( + match, BaseExceptionGroup, [ValueError(1), KeyboardInterrupt(2)] + ) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, ExceptionGroup, [ValueError(1)]) + self.assertMatchesTemplate(rest, BaseExceptionGroup, [KeyboardInterrupt(2)]) + + # Match KeyboardInterrupt + match, rest = self.split_exception_group(eg, KeyboardInterrupt) + self.assertMatchesTemplate(match, BaseExceptionGroup, [KeyboardInterrupt(2)]) + self.assertMatchesTemplate(rest, ExceptionGroup, [ValueError(1)]) + + def test_split_ExceptionGroup_subclass_derive_and_new_overrides(self): + class EG(ExceptionGroup): + def __new__(cls, message, excs, code): + obj = super().__new__(cls, message, excs) + obj.code = code + return obj + + def derive(self, excs): + return EG(self.message, excs, self.code) + + try: + try: + try: + raise TypeError(2) + except TypeError as te: + raise EG("nested", [te], 101) + except EG as nested: + try: + raise ValueError(1) + except ValueError as ve: + raise EG("eg", [ve, nested], 42) + except EG as e: + e.add_note("hello") + eg = e + + self.assertMatchesTemplate(eg, EG, [ValueError(1), [TypeError(2)]]) + + # Match Nothing + match, rest = self.split_exception_group(eg, OSError) + self.assertIsNone(match) + self.assertMatchesTemplate(rest, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[1].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match Everything + match, rest = self.split_exception_group(eg, (ValueError, TypeError)) + self.assertMatchesTemplate(match, EG, [ValueError(1), [TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[1].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertIsNone(rest) + + # Match ValueErrors + match, rest = self.split_exception_group(eg, ValueError) + self.assertMatchesTemplate(match, EG, [ValueError(1)]) + self.assertEqual(match.code, 42) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [[TypeError(2)]]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.exceptions[0].code, 101) + self.assertEqual(rest.__notes__, ["hello"]) + + # Match TypeErrors + match, rest = self.split_exception_group(eg, TypeError) + self.assertMatchesTemplate(match, EG, [[TypeError(2)]]) + self.assertEqual(match.code, 42) + self.assertEqual(match.exceptions[0].code, 101) + self.assertEqual(match.__notes__, ["hello"]) + self.assertMatchesTemplate(rest, EG, [ValueError(1)]) + self.assertEqual(rest.code, 42) + self.assertEqual(rest.__notes__, ["hello"]) + + +def test_repr(): + group = BaseExceptionGroup("foo", [ValueError(1), KeyboardInterrupt()]) + assert repr(group) == ( + "BaseExceptionGroup('foo', [ValueError(1), KeyboardInterrupt()])" + ) + + group = ExceptionGroup("foo", [ValueError(1), RuntimeError("bar")]) + assert repr(group) == "ExceptionGroup('foo', [ValueError(1), RuntimeError('bar')])" diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_formatting.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_formatting.py new file mode 100644 index 0000000000000000000000000000000000000000..557fcc839e0d3c8d510d46c10c2003974f889e36 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_formatting.py @@ -0,0 +1,558 @@ +import sys +import traceback +from typing import NoReturn +from urllib.error import HTTPError + +import pytest +from _pytest.capture import CaptureFixture +from _pytest.fixtures import SubRequest +from _pytest.monkeypatch import MonkeyPatch + +from exceptiongroup import ExceptionGroup + + +def raise_excgroup() -> NoReturn: + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + exc = ExceptionGroup("test message", exceptions) + exc.add_note("Displays notes attached to the group too") + raise exc + + +@pytest.fixture( + params=[ + pytest.param(True, id="patched"), + pytest.param( + False, + id="unpatched", + marks=[ + pytest.mark.skipif( + sys.version_info >= (3, 11), + reason="No patching is done on Python >= 3.11", + ) + ], + ), + ], +) +def patched(request: SubRequest) -> bool: + return request.param + + +@pytest.fixture( + params=[pytest.param(False, id="newstyle"), pytest.param(True, id="oldstyle")] +) +def old_argstyle(request: SubRequest) -> bool: + return request.param + + +def test_exceptionhook(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in test_exceptionhook + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_exceptiongroup_as_cause(capsys: CaptureFixture) -> None: + try: + raise Exception() from ExceptionGroup("", (Exception(),)) + except Exception as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_as_cause.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception + +------------------------------------ + +The above exception was the direct cause of the following exception: + +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, in test_exceptiongroup_as_cause + raise Exception() from ExceptionGroup("", (Exception(),)) +Exception +""" + ) + + +def test_exceptiongroup_loop(capsys: CaptureFixture) -> None: + e0 = Exception("e0") + eg0 = ExceptionGroup("eg0", (e0,)) + eg1 = ExceptionGroup("eg1", (eg0,)) + + try: + raise eg0 from eg1 + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + lineno = test_exceptiongroup_loop.__code__.co_firstlineno + 6 + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + output = capsys.readouterr().err + assert output == ( + f"""\ + | {module_prefix}ExceptionGroup: eg1 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ + +The above exception was the direct cause of the following exception: + + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {lineno}, in test_exceptiongroup_loop + | raise eg0 from eg1 + | {module_prefix}ExceptionGroup: eg0 (1 sub-exception) + +-+---------------- 1 ---------------- + | Exception: e0 + +------------------------------------ +""" + ) + + +def test_exceptionhook_format_exception_only(capsys: CaptureFixture) -> None: + try: + raise_excgroup() + except ExceptionGroup as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + local_lineno = test_exceptionhook_format_exception_only.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 2}, in \ +test_exceptionhook_format_exception_only + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_formatting_syntax_error(capsys: CaptureFixture) -> None: + try: + exec("//serser") + except SyntaxError as exc: + sys.excepthook(type(exc), exc, exc.__traceback__) + + if sys.version_info >= (3, 10): + underline = "\n ^^" + elif sys.version_info >= (3, 8): + underline = "\n ^" + else: + underline = "\n ^" + + lineno = test_formatting_syntax_error.__code__.co_firstlineno + underline_suffix = "" if sys.version_info < (3, 13) else "\n ~~~~^^^^^^^^^^^^" + output = capsys.readouterr().err + assert output == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {lineno + 2}, \ +in test_formatting_syntax_error + exec("//serser"){underline_suffix} + File "", line 1 + //serser{underline} +SyntaxError: invalid syntax +""" + ) + + +def test_format_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + exceptions = [] + try: + raise ValueError("foo") + except ValueError as exc: + exceptions.append(exc) + + try: + raise RuntimeError("bar") + except RuntimeError as exc: + exc.__notes__ = ["Note from bar handler"] + exceptions.append(exc) + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + lines = format_exception(type(exc), exc, exc.__traceback__) + else: + lines = format_exception(exc) + + local_lineno = test_format_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + assert isinstance(lines, list) + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + assert "".join(lines) == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 25}, in test_format_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_format_nested(monkeypatch: MonkeyPatch) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception + + def raise_exc(max_level: int, level: int = 1) -> NoReturn: + if level == max_level: + raise Exception(f"LEVEL_{level}") + else: + try: + raise_exc(max_level, level + 1) + except Exception: + raise Exception(f"LEVEL_{level}") + + try: + raise_exc(3) + except Exception as exc: + lines = format_exception(type(exc), exc, exc.__traceback__) + + underline_suffix1 = ( + "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^" + ) + underline_suffix2 = "" if sys.version_info < (3, 13) else "\n ~~~~~~~~~^^^" + local_lineno = test_format_nested.__code__.co_firstlineno + 20 + raise_exc_lineno1 = raise_exc.__code__.co_firstlineno + 2 + raise_exc_lineno2 = raise_exc.__code__.co_firstlineno + 5 + raise_exc_lineno3 = raise_exc.__code__.co_firstlineno + 7 + assert isinstance(lines, list) + assert "".join(lines) == ( + f"""\ +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno1}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_3 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {raise_exc_lineno2}, in raise_exc + raise_exc(max_level, level + 1){underline_suffix1} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_2 + +During handling of the above exception, another exception occurred: + +Traceback (most recent call last): + File "{__file__}", line {local_lineno}, in test_format_nested + raise_exc(3){underline_suffix2} + File "{__file__}", line {raise_exc_lineno3}, in raise_exc + raise Exception(f"LEVEL_{{level}}") +Exception: LEVEL_1 +""" + ) + + +def test_format_exception_only( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import format_exception_only + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + output = format_exception_only(type(exc), exc) + else: + output = format_exception_only(exc) + + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + assert output == [ + f"{module_prefix}ExceptionGroup: test message (2 sub-exceptions)\n", + "Displays notes attached to the group too\n", + ] + + +def test_print_exception( + patched: bool, old_argstyle: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + raise_excgroup() + except ExceptionGroup as exc: + if old_argstyle: + print_exception(type(exc), exc, exc.__traceback__) + else: + print_exception(exc) + + local_lineno = test_print_exception.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exception + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +def test_print_exc( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + raise_excgroup() + except ExceptionGroup: + print_exc() + local_lineno = test_print_exc.__code__.co_firstlineno + lineno = raise_excgroup.__code__.co_firstlineno + module_prefix = "" if sys.version_info >= (3, 11) else "exceptiongroup." + underline_suffix = ( + "" if sys.version_info < (3, 13) else "\n | ~~~~~~~~~~~~~~^^" + ) + output = capsys.readouterr().err + assert output == ( + f"""\ + + Exception Group Traceback (most recent call last): + | File "{__file__}", line {local_lineno + 13}, in test_print_exc + | raise_excgroup(){underline_suffix} + | File "{__file__}", line {lineno + 15}, in raise_excgroup + | raise exc + | {module_prefix}ExceptionGroup: test message (2 sub-exceptions) + | Displays notes attached to the group too + +-+---------------- 1 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 3}, in raise_excgroup + | raise ValueError("foo") + | ValueError: foo + +---------------- 2 ---------------- + | Traceback (most recent call last): + | File "{__file__}", line {lineno + 8}, in raise_excgroup + | raise RuntimeError("bar") + | RuntimeError: bar + | Note from bar handler + +------------------------------------ +""" + ) + + +@pytest.mark.skipif( + not hasattr(NameError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if NameError exposes the missing name", +) +def test_nameerror_suggestions( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exc + + try: + folder + except NameError: + print_exc() + output = capsys.readouterr().err + assert "Did you mean" in output and "'filter'?" in output + + +@pytest.mark.skipif( + not hasattr(AttributeError, "name") or sys.version_info[:2] == (3, 11), + reason="only works if AttributeError exposes the missing name", +) +def test_nameerror_suggestions_in_group( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + try: + [].attend + except AttributeError as e: + eg = ExceptionGroup("a", [e]) + print_exception(eg) + output = capsys.readouterr().err + assert "Did you mean" in output and "'append'?" in output + + +def test_bug_suggestions_attributeerror_no_obj( + patched: bool, monkeypatch: MonkeyPatch, capsys: CaptureFixture +) -> None: + if not patched: + # Block monkey patching, then force the module to be re-imported + del sys.modules["traceback"] + del sys.modules["exceptiongroup"] + del sys.modules["exceptiongroup._formatting"] + monkeypatch.setattr(sys, "excepthook", lambda *args: sys.__excepthook__(*args)) + + from exceptiongroup import print_exception + + class NamedAttributeError(AttributeError): + def __init__(self, name: str) -> None: + self.name: str = name + + try: + raise NamedAttributeError(name="mykey") + except AttributeError as e: + print_exception(e) # does not crash + output = capsys.readouterr().err + assert "NamedAttributeError" in output + + +def test_works_around_httperror_bug(): + # See https://github.com/python/cpython/issues/98778 in Python <= 3.9 + err = HTTPError("url", 405, "METHOD NOT ALLOWED", None, None) + traceback.TracebackException(type(err), err, None) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_suppress.py b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_suppress.py new file mode 100644 index 0000000000000000000000000000000000000000..289bb33c0e67fb99b149a306c9e32db8455cbb52 --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/tests/trusted/tests/test_suppress.py @@ -0,0 +1,16 @@ +import sys + +import pytest + +from exceptiongroup import suppress + +if sys.version_info < (3, 11): + from exceptiongroup import BaseExceptionGroup, ExceptionGroup + + +def test_suppress_exception(): + with pytest.raises(ExceptionGroup) as exc, suppress(SystemExit): + raise BaseExceptionGroup("", [SystemExit(1), RuntimeError("boo")]) + + assert len(exc.value.exceptions) == 1 + assert isinstance(exc.value.exceptions[0], RuntimeError) diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/validation/canaries/original-bug.sh b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..927547df786c86ab3bb5eeb917a31e0fa1895f8b --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -Eeuo pipefail +: diff --git a/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/validation/openenv.json b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..a13b3c577df494f6c894584d2b608ab051ebc44f --- /dev/null +++ b/tasks/agronholm__exceptiongroup.0b4f4937.func_basic__4wpmrn0g/validation/openenv.json @@ -0,0 +1,27 @@ +{ + "canaries": "validation/canaries", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 2, + "disk_mb": 16384, + "episode_timeout_s": 1800, + "memory_mb": 8192 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "python", + "mutation-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..c61d3249cacb7ec8c47508789e4f5c5d6a19983f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err != nil { + hash := readHashFromEntry(oldest) + if hash != 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5bb310064f51c0ca9eccb4652672038ba4cc7085 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/instruction.md @@ -0,0 +1,42 @@ +Cache crashes with slice bounds out of range when removing oldest entry + +#### Description + +When the cache needs to evict the oldest entry due to capacity constraints, it crashes with a "slice bounds out of range [8:0]" panic. This happens during normal cache operations when the cache is full and needs to make space for new entries. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + config.Shards = 1 + config.MaxEntrySize = 1024 + + cache, _ := bigcache.NewBigCache(config) + + // Fill cache to capacity + for i := 0; i < 1000; i++ { + key := fmt.Sprintf("key%d", i) + value := make([]byte, 500) // Large enough to trigger eviction + cache.Set(key, value) + } + + // This should trigger oldest entry removal and cause panic + cache.Set("trigger", make([]byte, 500)) +} +``` + +The panic occurs in the `removeOldestEntry` function when trying to read the hash from an entry that was popped from an empty queue. + +#### Environment + +- Go version: 1.21+ +- BigCache version: v3 +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..72eb38bd89c4586a4386d5c09ecf33e7a5f2546d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "5f9e645d85cd4c80a203688936413b6f9576253d0ba8910df16fa91987679ba7", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "495fdf3104e445b9ffb88b9bd90f078cb26d0375afd8b3d001001f413f392d71", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "ac660e776384c79e78533f6686d4fcf1852e4cda8026abb93e87947c5eddc102", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "4b8d384b13b9ba29c35ae9a43ef6baeac3e0009279653d23c2f1a52a8445ed98", + "is_fork": true, + "learner_path": "tasks/a27e8e2c9f851939f479682f/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/62d2518f6657099a8ad0139523c777cda2467bed/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "a290f76ae18b8eae067b7b69195baf4b47421f610b17a908f6b53e5cb939c193", + "provenance_path": "tasks/a27e8e2c9f851939f479682f/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "62d2518f6657099a8ad0139523c777cda2467bed", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "04fea6c72c075842120e98fcf211632565ee073f", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo", + "task_sha256": "ac268cf6dcb8c6f4c83f86a9dc6da4406f209d79fd1455ab84931f0a4accf8d1", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "66a7c24210a9f08d5ed5ce3e342ec048280f3e74aa6821eb0b2bc93da24aa20d", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a73356f1e7514155ea2de6f64b67d4a1c9d3878 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"shard.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlcnJvcnMiCgkic3luYyIKCSJzeW5jL2F0b21pYyIKCgkiZ2l0aHViLmNvbS9hbGxlZ3JvL2JpZ2NhY2hlL3YzL3F1ZXVlIgopCgp0eXBlIG9uUmVtb3ZlQ2FsbGJhY2sgZnVuYyh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKQoKLy8gTWV0YWRhdGEgY29udGFpbnMgaW5mb3JtYXRpb24gb2YgYSBzcGVjaWZpYyBlbnRyeQp0eXBlIE1ldGFkYXRhIHN0cnVjdCB7CglSZXF1ZXN0Q291bnQgdWludDMyCn0KCnR5cGUgY2FjaGVTaGFyZCBzdHJ1Y3QgewoJaGFzaG1hcCAgICAgbWFwW3VpbnQ2NF11aW50NjQKCWVudHJpZXMgICAgIHF1ZXVlLkJ5dGVzUXVldWUKCWxvY2sgICAgICAgIHN5bmMuUldNdXRleAoJZW50cnlCdWZmZXIgW11ieXRlCglvblJlbW92ZSAgICBvblJlbW92ZUNhbGxiYWNrCgoJaXNWZXJib3NlICAgIGJvb2wKCXN0YXRzRW5hYmxlZCBib29sCglsb2dnZXIgICAgICAgTG9nZ2VyCgljbG9jayAgICAgICAgY2xvY2sKCWxpZmVXaW5kb3cgICB1aW50NjQKCgloYXNobWFwU3RhdHMgbWFwW3VpbnQ2NF11aW50MzIKCXN0YXRzICAgICAgICBTdGF0cwoJY2xlYW5FbmFibGVkIGJvb2wKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZ2V0V2l0aEluZm8oa2V5IHN0cmluZywgaGFzaGVkS2V5IHVpbnQ2NCkgKGVudHJ5IFtdYnl0ZSwgcmVzcCBSZXNwb25zZSwgZXJyIGVycm9yKSB7CgljdXJyZW50VGltZSA6PSB1aW50NjQocy5jbG9jay5FcG9jaCgpKQoJcy5sb2NrLlJMb2NrKCkKCXdyYXBwZWRFbnRyeSwgZXJyIDo9IHMuZ2V0V3JhcHBlZEVudHJ5KGhhc2hlZEtleSkKCWlmIGVyciAhPSBuaWwgewoJCXMubG9jay5SVW5sb2NrKCkKCQlyZXR1cm4gbmlsLCByZXNwLCBlcnIKCX0KCWlmIGVudHJ5S2V5IDo9IHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KTsga2V5ICE9IGVudHJ5S2V5IHsKCQlzLmxvY2suUlVubG9jaygpCgkJcy5jb2xsaXNpb24oKQoJCWlmIHMuaXNWZXJib3NlIHsKCQkJcy5sb2dnZXIuUHJpbnRmKCJDb2xsaXNpb24gZGV0ZWN0ZWQuIEJvdGggJXEgYW5kICVxIGhhdmUgdGhlIHNhbWUgaGFzaCAleCIsIGtleSwgZW50cnlLZXksIGhhc2hlZEtleSkKCQl9CgkJcmV0dXJuIG5pbCwgcmVzcCwgRXJyRW50cnlOb3RGb3VuZAoJfQoKCWVudHJ5ID0gcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkKCWlmIHMuaXNFeHBpcmVkKHdyYXBwZWRFbnRyeSwgY3VycmVudFRpbWUpIHsKCQlyZXNwLkVudHJ5U3RhdHVzID0gRXhwaXJlZAoJfQoJcy5sb2NrLlJVbmxvY2soKQoJcy5oaXQoaGFzaGVkS2V5KQoJcmV0dXJuIGVudHJ5LCByZXNwLCBuaWwKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZ2V0KGtleSBzdHJpbmcsIGhhc2hlZEtleSB1aW50NjQpIChbXWJ5dGUsIGVycm9yKSB7CglzLmxvY2suUkxvY2soKQoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJaWYgZXJyICE9IG5pbCB7CgkJcy5sb2NrLlJVbmxvY2soKQoJCXJldHVybiBuaWwsIGVycgoJfQoJaWYgZW50cnlLZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpOyBrZXkgIT0gZW50cnlLZXkgewoJCXMubG9jay5SVW5sb2NrKCkKCQlzLmNvbGxpc2lvbigpCgkJaWYgcy5pc1ZlcmJvc2UgewoJCQlzLmxvZ2dlci5QcmludGYoIkNvbGxpc2lvbiBkZXRlY3RlZC4gQm90aCAlcSBhbmQgJXEgaGF2ZSB0aGUgc2FtZSBoYXNoICV4Iiwga2V5LCBlbnRyeUtleSwgaGFzaGVkS2V5KQoJCX0KCQlyZXR1cm4gbmlsLCBFcnJFbnRyeU5vdEZvdW5kCgl9CgllbnRyeSA6PSByZWFkRW50cnkod3JhcHBlZEVudHJ5KQoJcy5sb2NrLlJVbmxvY2soKQoJcy5oaXQoaGFzaGVkS2V5KQoKCXJldHVybiBlbnRyeSwgbmlsCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldFdyYXBwZWRFbnRyeShoYXNoZWRLZXkgdWludDY0KSAoW11ieXRlLCBlcnJvcikgewoJaXRlbUluZGV4IDo9IHMuaGFzaG1hcFtoYXNoZWRLZXldCgoJaWYgaXRlbUluZGV4ID09IDAgewoJCXMubWlzcygpCgkJcmV0dXJuIG5pbCwgRXJyRW50cnlOb3RGb3VuZAoJfQoKCXdyYXBwZWRFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KGl0ZW1JbmRleCkpCglpZiBlcnIgIT0gbmlsIHsKCQlzLm1pc3MoKQoJCXJldHVybiBuaWwsIGVycgoJfQoKCXJldHVybiB3cmFwcGVkRW50cnksIGVycgp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBnZXRWYWxpZFdyYXBFbnRyeShrZXkgc3RyaW5nLCBoYXNoZWRLZXkgdWludDY0KSAoW11ieXRlLCBlcnJvcikgewoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgZXJyCgl9CgoJaWYgIWNvbXBhcmVLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5LCBrZXkpIHsKCQlzLmNvbGxpc2lvbigpCgkJaWYgcy5pc1ZlcmJvc2UgewoJCQlzLmxvZ2dlci5QcmludGYoIkNvbGxpc2lvbiBkZXRlY3RlZC4gQm90aCAlcSBhbmQgJXEgaGF2ZSB0aGUgc2FtZSBoYXNoICV4Iiwga2V5LCByZWFkS2V5RnJvbUVudHJ5KHdyYXBwZWRFbnRyeSksIGhhc2hlZEtleSkKCQl9CgoJCXJldHVybiBuaWwsIEVyckVudHJ5Tm90Rm91bmQKCX0KCXMuaGl0V2l0aG91dExvY2soaGFzaGVkS2V5KQoKCXJldHVybiB3cmFwcGVkRW50cnksIG5pbAp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBzZXQoa2V5IHN0cmluZywgaGFzaGVkS2V5IHVpbnQ2NCwgZW50cnkgW11ieXRlKSBlcnJvciB7CgljdXJyZW50VGltZXN0YW1wIDo9IHVpbnQ2NChzLmNsb2NrLkVwb2NoKCkpCgoJcy5sb2NrLkxvY2soKQoKCWlmIHByZXZpb3VzSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV07IHByZXZpb3VzSW5kZXggIT0gMCB7CgkJaWYgcHJldmlvdXNFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KHByZXZpb3VzSW5kZXgpKTsgZXJyID09IG5pbCB7CgkJCXJlc2V0SGFzaEZyb21FbnRyeShwcmV2aW91c0VudHJ5KQoJCQkvL3JlbW92ZSBoYXNoa2V5CgkJCWRlbGV0ZShzLmhhc2htYXAsIGhhc2hlZEtleSkKCQl9Cgl9CgoJaWYgIXMuY2xlYW5FbmFibGVkIHsKCQlpZiBvbGRlc3RFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5QZWVrKCk7IGVyciA9PSBuaWwgewoJCQlzLm9uRXZpY3Qob2xkZXN0RW50cnksIGN1cnJlbnRUaW1lc3RhbXAsIHMucmVtb3ZlT2xkZXN0RW50cnkpCgkJfQoJfQoKCXcgOj0gd3JhcEVudHJ5KGN1cnJlbnRUaW1lc3RhbXAsIGhhc2hlZEtleSwga2V5LCBlbnRyeSwgJnMuZW50cnlCdWZmZXIpCgoJZm9yIHsKCQlpZiBpbmRleCwgZXJyIDo9IHMuZW50cmllcy5QdXNoKHcpOyBlcnIgPT0gbmlsIHsKCQkJcy5oYXNobWFwW2hhc2hlZEtleV0gPSB1aW50NjQoaW5kZXgpCgkJCXMubG9jay5VbmxvY2soKQoJCQlyZXR1cm4gbmlsCgkJfQoJCWlmIHMucmVtb3ZlT2xkZXN0RW50cnkoTm9TcGFjZSkgIT0gbmlsIHsKCQkJcy5sb2NrLlVubG9jaygpCgkJCXJldHVybiBlcnJvcnMuTmV3KCJlbnRyeSBpcyBiaWdnZXIgdGhhbiBtYXggc2hhcmQgc2l6ZSIpCgkJfQoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBhZGROZXdXaXRob3V0TG9jayhrZXkgc3RyaW5nLCBoYXNoZWRLZXkgdWludDY0LCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWN1cnJlbnRUaW1lc3RhbXAgOj0gdWludDY0KHMuY2xvY2suRXBvY2goKSkKCglpZiAhcy5jbGVhbkVuYWJsZWQgewoJCWlmIG9sZGVzdEVudHJ5LCBlcnIgOj0gcy5lbnRyaWVzLlBlZWsoKTsgZXJyID09IG5pbCB7CgkJCXMub25FdmljdChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCwgcy5yZW1vdmVPbGRlc3RFbnRyeSkKCQl9Cgl9CgoJdyA6PSB3cmFwRW50cnkoY3VycmVudFRpbWVzdGFtcCwgaGFzaGVkS2V5LCBrZXksIGVudHJ5LCAmcy5lbnRyeUJ1ZmZlcikKCglmb3IgewoJCWlmIGluZGV4LCBlcnIgOj0gcy5lbnRyaWVzLlB1c2godyk7IGVyciA9PSBuaWwgewoJCQlzLmhhc2htYXBbaGFzaGVkS2V5XSA9IHVpbnQ2NChpbmRleCkKCQkJcmV0dXJuIG5pbAoJCX0KCQlpZiBzLnJlbW92ZU9sZGVzdEVudHJ5KE5vU3BhY2UpICE9IG5pbCB7CgkJCXJldHVybiBlcnJvcnMuTmV3KCJlbnRyeSBpcyBiaWdnZXIgdGhhbiBtYXggc2hhcmQgc2l6ZSIpCgkJfQoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBzZXRXcmFwcGVkRW50cnlXaXRob3V0TG9jayhjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgdyBbXWJ5dGUsIGhhc2hlZEtleSB1aW50NjQpIGVycm9yIHsKCWlmIHByZXZpb3VzSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV07IHByZXZpb3VzSW5kZXggIT0gMCB7CgkJaWYgcHJldmlvdXNFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KHByZXZpb3VzSW5kZXgpKTsgZXJyID09IG5pbCB7CgkJCXJlc2V0SGFzaEZyb21FbnRyeShwcmV2aW91c0VudHJ5KQoJCX0KCX0KCglpZiAhcy5jbGVhbkVuYWJsZWQgewoJCWlmIG9sZGVzdEVudHJ5LCBlcnIgOj0gcy5lbnRyaWVzLlBlZWsoKTsgZXJyID09IG5pbCB7CgkJCXMub25FdmljdChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCwgcy5yZW1vdmVPbGRlc3RFbnRyeSkKCQl9Cgl9CgoJZm9yIHsKCQlpZiBpbmRleCwgZXJyIDo9IHMuZW50cmllcy5QdXNoKHcpOyBlcnIgPT0gbmlsIHsKCQkJcy5oYXNobWFwW2hhc2hlZEtleV0gPSB1aW50NjQoaW5kZXgpCgkJCXJldHVybiBuaWwKCQl9CgkJaWYgcy5yZW1vdmVPbGRlc3RFbnRyeShOb1NwYWNlKSAhPSBuaWwgewoJCQlyZXR1cm4gZXJyb3JzLk5ldygiZW50cnkgaXMgYmlnZ2VyIHRoYW4gbWF4IHNoYXJkIHNpemUiKQoJCX0KCX0KfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgYXBwZW5kKGtleSBzdHJpbmcsIGhhc2hlZEtleSB1aW50NjQsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJcy5sb2NrLkxvY2soKQoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRWYWxpZFdyYXBFbnRyeShrZXksIGhhc2hlZEtleSkKCglpZiBlcnIgPT0gRXJyRW50cnlOb3RGb3VuZCB7CgkJZXJyID0gcy5hZGROZXdXaXRob3V0TG9jayhrZXksIGhhc2hlZEtleSwgZW50cnkpCgkJcy5sb2NrLlVubG9jaygpCgkJcmV0dXJuIGVycgoJfQoJaWYgZXJyICE9IG5pbCB7CgkJcy5sb2NrLlVubG9jaygpCgkJcmV0dXJuIGVycgoJfQoKCWN1cnJlbnRUaW1lc3RhbXAgOj0gdWludDY0KHMuY2xvY2suRXBvY2goKSkKCgl3IDo9IGFwcGVuZFRvV3JhcHBlZEVudHJ5KGN1cnJlbnRUaW1lc3RhbXAsIHdyYXBwZWRFbnRyeSwgZW50cnksICZzLmVudHJ5QnVmZmVyKQoKCWVyciA9IHMuc2V0V3JhcHBlZEVudHJ5V2l0aG91dExvY2soY3VycmVudFRpbWVzdGFtcCwgdywgaGFzaGVkS2V5KQoJcy5sb2NrLlVubG9jaygpCgoJcmV0dXJuIGVycgp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBkZWwoaGFzaGVkS2V5IHVpbnQ2NCkgZXJyb3IgewoJLy8gT3B0aW1pc3RpYyBwcmUtY2hlY2sgdXNpbmcgb25seSByZWFkbG9jawoJcy5sb2NrLlJMb2NrKCkKCXsKCQlpdGVtSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV0KCgkJaWYgaXRlbUluZGV4ID09IDAgewoJCQlzLmxvY2suUlVubG9jaygpCgkJCXMuZGVsbWlzcygpCgkJCXJldHVybiBFcnJFbnRyeU5vdEZvdW5kCgkJfQoKCQlpZiBlcnIgOj0gcy5lbnRyaWVzLkNoZWNrR2V0KGludChpdGVtSW5kZXgpKTsgZXJyICE9IG5pbCB7CgkJCXMubG9jay5SVW5sb2NrKCkKCQkJcy5kZWxtaXNzKCkKCQkJcmV0dXJuIGVycgoJCX0KCX0KCXMubG9jay5SVW5sb2NrKCkKCglzLmxvY2suTG9jaygpCgl7CgkJLy8gQWZ0ZXIgb2J0YWluaW5nIHRoZSB3cml0ZWxvY2ssIHdlIG5lZWQgdG8gcmVhZCB0aGUgc2FtZSBhZ2FpbiwKCQkvLyBzaW5jZSB0aGUgZGF0YSBkZWxpdmVyZWQgZWFybGllciBtYXkgYmUgc3RhbGUgbm93CgkJaXRlbUluZGV4IDo9IHMuaGFzaG1hcFtoYXNoZWRLZXldCgoJCWlmIGl0ZW1JbmRleCA9PSAwIHsKCQkJcy5sb2NrLlVubG9jaygpCgkJCXMuZGVsbWlzcygpCgkJCXJldHVybiBFcnJFbnRyeU5vdEZvdW5kCgkJfQoKCQl3cmFwcGVkRW50cnksIGVyciA6PSBzLmVudHJpZXMuR2V0KGludChpdGVtSW5kZXgpKQoJCWlmIGVyciAhPSBuaWwgewoJCQlzLmxvY2suVW5sb2NrKCkKCQkJcy5kZWxtaXNzKCkKCQkJcmV0dXJuIGVycgoJCX0KCgkJZGVsZXRlKHMuaGFzaG1hcCwgaGFzaGVkS2V5KQoJCXMub25SZW1vdmUod3JhcHBlZEVudHJ5LCBEZWxldGVkKQoJCWlmIHMuc3RhdHNFbmFibGVkIHsKCQkJZGVsZXRlKHMuaGFzaG1hcFN0YXRzLCBoYXNoZWRLZXkpCgkJfQoJCXJlc2V0SGFzaEZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgl9CglzLmxvY2suVW5sb2NrKCkKCglzLmRlbGhpdCgpCglyZXR1cm4gbmlsCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglpZiBzLmlzRXhwaXJlZChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCkgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBpc0V4cGlyZWQob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPD0gb2xkZXN0VGltZXN0YW1wIHsgLy8gaWYgY3VycmVudFRpbWVzdGFtcCA8IG9sZGVzdFRpbWVzdGFtcCwgdGhlIHJlc3VsdCB3aWxsIG91dCBvZiB1aW50NjQgbGltaXRzOwoJCXJldHVybiBmYWxzZQoJfQoJcmV0dXJuIGN1cnJlbnRUaW1lc3RhbXAtb2xkZXN0VGltZXN0YW1wID4gcy5saWZlV2luZG93Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGNsZWFuVXAoY3VycmVudFRpbWVzdGFtcCB1aW50NjQpIHsKCXMubG9jay5Mb2NrKCkKCWZvciB7CgkJaWYgb2xkZXN0RW50cnksIGVyciA6PSBzLmVudHJpZXMuUGVlaygpOyBlcnIgIT0gbmlsIHsKCQkJYnJlYWsKCQl9IGVsc2UgaWYgZXZpY3RlZCA6PSBzLm9uRXZpY3Qob2xkZXN0RW50cnksIGN1cnJlbnRUaW1lc3RhbXAsIHMucmVtb3ZlT2xkZXN0RW50cnkpOyAhZXZpY3RlZCB7CgkJCWJyZWFrCgkJfQoJfQoJcy5sb2NrLlVubG9jaygpCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldEVudHJ5KGhhc2hlZEtleSB1aW50NjQpIChbXWJ5dGUsIGVycm9yKSB7CglzLmxvY2suUkxvY2soKQoKCWVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJLy8gY29weSBlbnRyeQoJbmV3RW50cnkgOj0gbWFrZShbXWJ5dGUsIGxlbihlbnRyeSkpCgljb3B5KG5ld0VudHJ5LCBlbnRyeSkKCglzLmxvY2suUlVubG9jaygpCgoJcmV0dXJuIG5ld0VudHJ5LCBlcnIKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgY29weUhhc2hlZEtleXMoKSAoa2V5cyBbXXVpbnQ2NCwgbmV4dCBpbnQpIHsKCXMubG9jay5STG9jaygpCglrZXlzID0gbWFrZShbXXVpbnQ2NCwgbGVuKHMuaGFzaG1hcCkpCgoJZm9yIGtleSA6PSByYW5nZSBzLmhhc2htYXAgewoJCWtleXNbbmV4dF0gPSBrZXkKCQluZXh0KysKCX0KCglzLmxvY2suUlVubG9jaygpCglyZXR1cm4ga2V5cywgbmV4dAp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSByZW1vdmVPbGRlc3RFbnRyeShyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvciB7CglvbGRlc3QsIGVyciA6PSBzLmVudHJpZXMuUG9wKCkKCWlmIGVyciA9PSBuaWwgewoJCWhhc2ggOj0gcmVhZEhhc2hGcm9tRW50cnkob2xkZXN0KQoJCWlmIGhhc2ggPT0gMCB7CgkJCS8vIGVudHJ5IGhhcyBiZWVuIGV4cGxpY2l0bHkgZGVsZXRlZCB3aXRoIHJlc2V0SGFzaEZyb21FbnRyeSwgaWdub3JlCgkJCXJldHVybiBuaWwKCQl9CgkJZGVsZXRlKHMuaGFzaG1hcCwgaGFzaCkKCQlzLm9uUmVtb3ZlKG9sZGVzdCwgcmVhc29uKQoJCWlmIHMuc3RhdHNFbmFibGVkIHsKCQkJZGVsZXRlKHMuaGFzaG1hcFN0YXRzLCBoYXNoKQoJCX0KCQlyZXR1cm4gbmlsCgl9CglyZXR1cm4gZXJyCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIHJlc2V0KGNvbmZpZyBDb25maWcpIHsKCXMubG9jay5Mb2NrKCkKCXMuaGFzaG1hcCA9IG1ha2UobWFwW3VpbnQ2NF11aW50NjQsIGNvbmZpZy5pbml0aWFsU2hhcmRTaXplKCkpCglzLmVudHJ5QnVmZmVyID0gbWFrZShbXWJ5dGUsIGNvbmZpZy5NYXhFbnRyeVNpemUraGVhZGVyc1NpemVJbkJ5dGVzKQoJcy5lbnRyaWVzLlJlc2V0KCkKCXMubG9jay5VbmxvY2soKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSByZXNldFN0YXRzKCkgewoJcy5sb2NrLkxvY2soKQoJcy5zdGF0cyA9IFN0YXRze30KCXMubG9jay5VbmxvY2soKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBsZW4oKSBpbnQgewoJcy5sb2NrLlJMb2NrKCkKCXJlcyA6PSBsZW4ocy5oYXNobWFwKQoJcy5sb2NrLlJVbmxvY2soKQoJcmV0dXJuIHJlcwp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBjYXBhY2l0eSgpIGludCB7CglzLmxvY2suUkxvY2soKQoJcmVzIDo9IHMuZW50cmllcy5DYXBhY2l0eSgpCglzLmxvY2suUlVubG9jaygpCglyZXR1cm4gcmVzCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldFN0YXRzKCkgU3RhdHMgewoJdmFyIHN0YXRzID0gU3RhdHN7CgkJSGl0czogICAgICAgYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5IaXRzKSwKCQlNaXNzZXM6ICAgICBhdG9taWMuTG9hZEludDY0KCZzLnN0YXRzLk1pc3NlcyksCgkJRGVsSGl0czogICAgYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5EZWxIaXRzKSwKCQlEZWxNaXNzZXM6ICBhdG9taWMuTG9hZEludDY0KCZzLnN0YXRzLkRlbE1pc3NlcyksCgkJQ29sbGlzaW9uczogYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5Db2xsaXNpb25zKSwKCX0KCXJldHVybiBzdGF0cwp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBnZXRLZXlNZXRhZGF0YVdpdGhMb2NrKGtleSB1aW50NjQpIE1ldGFkYXRhIHsKCXMubG9jay5STG9jaygpCgljIDo9IHMuaGFzaG1hcFN0YXRzW2tleV0KCXMubG9jay5SVW5sb2NrKCkKCXJldHVybiBNZXRhZGF0YXsKCQlSZXF1ZXN0Q291bnQ6IGMsCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldEtleU1ldGFkYXRhKGtleSB1aW50NjQpIE1ldGFkYXRhIHsKCXJldHVybiBNZXRhZGF0YXsKCQlSZXF1ZXN0Q291bnQ6IHMuaGFzaG1hcFN0YXRzW2tleV0sCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGhpdChrZXkgdWludDY0KSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuSGl0cywgMSkKCWlmIHMuc3RhdHNFbmFibGVkIHsKCQlzLmxvY2suTG9jaygpCgkJcy5oYXNobWFwU3RhdHNba2V5XSsrCgkJcy5sb2NrLlVubG9jaygpCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGhpdFdpdGhvdXRMb2NrKGtleSB1aW50NjQpIHsKCWF0b21pYy5BZGRJbnQ2NCgmcy5zdGF0cy5IaXRzLCAxKQoJaWYgcy5zdGF0c0VuYWJsZWQgewoJCXMuaGFzaG1hcFN0YXRzW2tleV0rKwoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBtaXNzKCkgewoJYXRvbWljLkFkZEludDY0KCZzLnN0YXRzLk1pc3NlcywgMSkKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZGVsaGl0KCkgewoJYXRvbWljLkFkZEludDY0KCZzLnN0YXRzLkRlbEhpdHMsIDEpCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGRlbG1pc3MoKSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuRGVsTWlzc2VzLCAxKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBjb2xsaXNpb24oKSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuQ29sbGlzaW9ucywgMSkKfQoKZnVuYyBpbml0TmV3U2hhcmQoY29uZmlnIENvbmZpZywgY2FsbGJhY2sgb25SZW1vdmVDYWxsYmFjaywgY2xvY2sgY2xvY2spICpjYWNoZVNoYXJkIHsKCWJ5dGVzUXVldWVJbml0aWFsQ2FwYWNpdHkgOj0gY29uZmlnLmluaXRpYWxTaGFyZFNpemUoKSAqIGNvbmZpZy5NYXhFbnRyeVNpemUKCW1heGltdW1TaGFyZFNpemVJbkJ5dGVzIDo9IGNvbmZpZy5tYXhpbXVtU2hhcmRTaXplSW5CeXRlcygpCglpZiBtYXhpbXVtU2hhcmRTaXplSW5CeXRlcyA+IDAgJiYgYnl0ZXNRdWV1ZUluaXRpYWxDYXBhY2l0eSA+IG1heGltdW1TaGFyZFNpemVJbkJ5dGVzIHsKCQlieXRlc1F1ZXVlSW5pdGlhbENhcGFjaXR5ID0gbWF4aW11bVNoYXJkU2l6ZUluQnl0ZXMKCX0KCXJldHVybiAmY2FjaGVTaGFyZHsKCQloYXNobWFwOiAgICAgIG1ha2UobWFwW3VpbnQ2NF11aW50NjQsIGNvbmZpZy5pbml0aWFsU2hhcmRTaXplKCkpLAoJCWhhc2htYXBTdGF0czogbWFrZShtYXBbdWludDY0XXVpbnQzMiwgY29uZmlnLmluaXRpYWxTaGFyZFNpemUoKSksCgkJZW50cmllczogICAgICAqcXVldWUuTmV3Qnl0ZXNRdWV1ZShieXRlc1F1ZXVlSW5pdGlhbENhcGFjaXR5LCBtYXhpbXVtU2hhcmRTaXplSW5CeXRlcywgY29uZmlnLlZlcmJvc2UpLAoJCWVudHJ5QnVmZmVyOiAgbWFrZShbXWJ5dGUsIGNvbmZpZy5NYXhFbnRyeVNpemUraGVhZGVyc1NpemVJbkJ5dGVzKSwKCQlvblJlbW92ZTogICAgIGNhbGxiYWNrLAoKCQlpc1ZlcmJvc2U6ICAgIGNvbmZpZy5WZXJib3NlLAoJCWxvZ2dlcjogICAgICAgbmV3TG9nZ2VyKGNvbmZpZy5Mb2dnZXIpLAoJCWNsb2NrOiAgICAgICAgY2xvY2ssCgkJbGlmZVdpbmRvdzogICB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKSwKCQlzdGF0c0VuYWJsZWQ6IGNvbmZpZy5TdGF0c0VuYWJsZWQsCgkJY2xlYW5FbmFibGVkOiBjb25maWcuQ2xlYW5XaW5kb3cgPiAwLAoJfQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f8f408f73f143afe8cba913f41c3f3f71bfdec2e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:78be8bd579a7d6249872c585495f8f0a246b3fd3cdb073d02d70772e40b27ae4" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..26b2b2093f15c3417e11c1207b04d8c98c5c7710 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/manifest.json @@ -0,0 +1,271 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..4b0f936c244f7cd1cb1ba2d88e875e8c2ad09641 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__mlplg9xo/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "5170a8f20adc9d669a8a35f103ec3c65bff75f9f8bd1dcce93ca8eb2beb6b999", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..76b47737350a13b9384d9cd7da4fc3ad044dcb3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err == nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d51c76ca13e7d74e23fdd7d2d68dfeb4bddb439 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/instruction.md @@ -0,0 +1,38 @@ +Cache retrieval returns nil for valid entries + +#### Description + +When retrieving entries from the cache, valid entries are being returned as nil instead of their actual values. This appears to affect cache hits where the entry exists and should be returned successfully. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + cache, _ := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute)) + + // Store a value + cache.Set("testkey", []byte("testvalue")) + + // Try to retrieve it + value, err := cache.Get("testkey") + if err != nil { + fmt.Printf("Error: %v\n", err) + } else { + fmt.Printf("Retrieved: %s\n", string(value)) + } + + // Expected: Retrieved: testvalue + // Actual: Error: Entry not found +} +``` + +The cache should return the stored value but instead returns an error indicating the entry was not found, even though it was just stored successfully. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b18bc50ee9117ef1063ab27835a0dafaf5ea310f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "80bb07c2f7fe7010ae79b919ba09fa5bdc4af2dda6ba93bee2fd8ddf7156273f", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "6fbaca021f35cc1e43f47fb6789908456e1b994362510ddd49088584e4360a02", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "e8eccbdc5c9c4fadbcd51f84f140f870b16d533c280ffead4688a86feefc88aa", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "51607a0231a11abf089e1fc99f82ffd3e3747d857dec0197b1707e7757ab8749", + "is_fork": true, + "learner_path": "tasks/ee99ee3afc3d644c8b31dd34/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/8e434d6b69c405c54482b523c7c5678709d5cd1f/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "f325a8f5899e1f7033cc2ca6724c8f8d31475330529f32b3b244b38399e4f45d", + "provenance_path": "tasks/ee99ee3afc3d644c8b31dd34/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "8e434d6b69c405c54482b523c7c5678709d5cd1f", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "cae510c88805c84b036cb0d10ef5a4164b35b29a", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd", + "task_sha256": "1ed29373be11d74996a39060039bc5b18808cc31b9c8180067f0b2b3bc4e0b7a", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "22385d42a2db034e218e67f9fc820c4c6b81c40b63b62356013bc44a997ceffe", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a73356f1e7514155ea2de6f64b67d4a1c9d3878 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"shard.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlcnJvcnMiCgkic3luYyIKCSJzeW5jL2F0b21pYyIKCgkiZ2l0aHViLmNvbS9hbGxlZ3JvL2JpZ2NhY2hlL3YzL3F1ZXVlIgopCgp0eXBlIG9uUmVtb3ZlQ2FsbGJhY2sgZnVuYyh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKQoKLy8gTWV0YWRhdGEgY29udGFpbnMgaW5mb3JtYXRpb24gb2YgYSBzcGVjaWZpYyBlbnRyeQp0eXBlIE1ldGFkYXRhIHN0cnVjdCB7CglSZXF1ZXN0Q291bnQgdWludDMyCn0KCnR5cGUgY2FjaGVTaGFyZCBzdHJ1Y3QgewoJaGFzaG1hcCAgICAgbWFwW3VpbnQ2NF11aW50NjQKCWVudHJpZXMgICAgIHF1ZXVlLkJ5dGVzUXVldWUKCWxvY2sgICAgICAgIHN5bmMuUldNdXRleAoJZW50cnlCdWZmZXIgW11ieXRlCglvblJlbW92ZSAgICBvblJlbW92ZUNhbGxiYWNrCgoJaXNWZXJib3NlICAgIGJvb2wKCXN0YXRzRW5hYmxlZCBib29sCglsb2dnZXIgICAgICAgTG9nZ2VyCgljbG9jayAgICAgICAgY2xvY2sKCWxpZmVXaW5kb3cgICB1aW50NjQKCgloYXNobWFwU3RhdHMgbWFwW3VpbnQ2NF11aW50MzIKCXN0YXRzICAgICAgICBTdGF0cwoJY2xlYW5FbmFibGVkIGJvb2wKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZ2V0V2l0aEluZm8oa2V5IHN0cmluZywgaGFzaGVkS2V5IHVpbnQ2NCkgKGVudHJ5IFtdYnl0ZSwgcmVzcCBSZXNwb25zZSwgZXJyIGVycm9yKSB7CgljdXJyZW50VGltZSA6PSB1aW50NjQocy5jbG9jay5FcG9jaCgpKQoJcy5sb2NrLlJMb2NrKCkKCXdyYXBwZWRFbnRyeSwgZXJyIDo9IHMuZ2V0V3JhcHBlZEVudHJ5KGhhc2hlZEtleSkKCWlmIGVyciAhPSBuaWwgewoJCXMubG9jay5SVW5sb2NrKCkKCQlyZXR1cm4gbmlsLCByZXNwLCBlcnIKCX0KCWlmIGVudHJ5S2V5IDo9IHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KTsga2V5ICE9IGVudHJ5S2V5IHsKCQlzLmxvY2suUlVubG9jaygpCgkJcy5jb2xsaXNpb24oKQoJCWlmIHMuaXNWZXJib3NlIHsKCQkJcy5sb2dnZXIuUHJpbnRmKCJDb2xsaXNpb24gZGV0ZWN0ZWQuIEJvdGggJXEgYW5kICVxIGhhdmUgdGhlIHNhbWUgaGFzaCAleCIsIGtleSwgZW50cnlLZXksIGhhc2hlZEtleSkKCQl9CgkJcmV0dXJuIG5pbCwgcmVzcCwgRXJyRW50cnlOb3RGb3VuZAoJfQoKCWVudHJ5ID0gcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkKCWlmIHMuaXNFeHBpcmVkKHdyYXBwZWRFbnRyeSwgY3VycmVudFRpbWUpIHsKCQlyZXNwLkVudHJ5U3RhdHVzID0gRXhwaXJlZAoJfQoJcy5sb2NrLlJVbmxvY2soKQoJcy5oaXQoaGFzaGVkS2V5KQoJcmV0dXJuIGVudHJ5LCByZXNwLCBuaWwKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZ2V0KGtleSBzdHJpbmcsIGhhc2hlZEtleSB1aW50NjQpIChbXWJ5dGUsIGVycm9yKSB7CglzLmxvY2suUkxvY2soKQoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJaWYgZXJyICE9IG5pbCB7CgkJcy5sb2NrLlJVbmxvY2soKQoJCXJldHVybiBuaWwsIGVycgoJfQoJaWYgZW50cnlLZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpOyBrZXkgIT0gZW50cnlLZXkgewoJCXMubG9jay5SVW5sb2NrKCkKCQlzLmNvbGxpc2lvbigpCgkJaWYgcy5pc1ZlcmJvc2UgewoJCQlzLmxvZ2dlci5QcmludGYoIkNvbGxpc2lvbiBkZXRlY3RlZC4gQm90aCAlcSBhbmQgJXEgaGF2ZSB0aGUgc2FtZSBoYXNoICV4Iiwga2V5LCBlbnRyeUtleSwgaGFzaGVkS2V5KQoJCX0KCQlyZXR1cm4gbmlsLCBFcnJFbnRyeU5vdEZvdW5kCgl9CgllbnRyeSA6PSByZWFkRW50cnkod3JhcHBlZEVudHJ5KQoJcy5sb2NrLlJVbmxvY2soKQoJcy5oaXQoaGFzaGVkS2V5KQoKCXJldHVybiBlbnRyeSwgbmlsCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldFdyYXBwZWRFbnRyeShoYXNoZWRLZXkgdWludDY0KSAoW11ieXRlLCBlcnJvcikgewoJaXRlbUluZGV4IDo9IHMuaGFzaG1hcFtoYXNoZWRLZXldCgoJaWYgaXRlbUluZGV4ID09IDAgewoJCXMubWlzcygpCgkJcmV0dXJuIG5pbCwgRXJyRW50cnlOb3RGb3VuZAoJfQoKCXdyYXBwZWRFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KGl0ZW1JbmRleCkpCglpZiBlcnIgIT0gbmlsIHsKCQlzLm1pc3MoKQoJCXJldHVybiBuaWwsIGVycgoJfQoKCXJldHVybiB3cmFwcGVkRW50cnksIGVycgp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBnZXRWYWxpZFdyYXBFbnRyeShrZXkgc3RyaW5nLCBoYXNoZWRLZXkgdWludDY0KSAoW11ieXRlLCBlcnJvcikgewoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgZXJyCgl9CgoJaWYgIWNvbXBhcmVLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5LCBrZXkpIHsKCQlzLmNvbGxpc2lvbigpCgkJaWYgcy5pc1ZlcmJvc2UgewoJCQlzLmxvZ2dlci5QcmludGYoIkNvbGxpc2lvbiBkZXRlY3RlZC4gQm90aCAlcSBhbmQgJXEgaGF2ZSB0aGUgc2FtZSBoYXNoICV4Iiwga2V5LCByZWFkS2V5RnJvbUVudHJ5KHdyYXBwZWRFbnRyeSksIGhhc2hlZEtleSkKCQl9CgoJCXJldHVybiBuaWwsIEVyckVudHJ5Tm90Rm91bmQKCX0KCXMuaGl0V2l0aG91dExvY2soaGFzaGVkS2V5KQoKCXJldHVybiB3cmFwcGVkRW50cnksIG5pbAp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBzZXQoa2V5IHN0cmluZywgaGFzaGVkS2V5IHVpbnQ2NCwgZW50cnkgW11ieXRlKSBlcnJvciB7CgljdXJyZW50VGltZXN0YW1wIDo9IHVpbnQ2NChzLmNsb2NrLkVwb2NoKCkpCgoJcy5sb2NrLkxvY2soKQoKCWlmIHByZXZpb3VzSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV07IHByZXZpb3VzSW5kZXggIT0gMCB7CgkJaWYgcHJldmlvdXNFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KHByZXZpb3VzSW5kZXgpKTsgZXJyID09IG5pbCB7CgkJCXJlc2V0SGFzaEZyb21FbnRyeShwcmV2aW91c0VudHJ5KQoJCQkvL3JlbW92ZSBoYXNoa2V5CgkJCWRlbGV0ZShzLmhhc2htYXAsIGhhc2hlZEtleSkKCQl9Cgl9CgoJaWYgIXMuY2xlYW5FbmFibGVkIHsKCQlpZiBvbGRlc3RFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5QZWVrKCk7IGVyciA9PSBuaWwgewoJCQlzLm9uRXZpY3Qob2xkZXN0RW50cnksIGN1cnJlbnRUaW1lc3RhbXAsIHMucmVtb3ZlT2xkZXN0RW50cnkpCgkJfQoJfQoKCXcgOj0gd3JhcEVudHJ5KGN1cnJlbnRUaW1lc3RhbXAsIGhhc2hlZEtleSwga2V5LCBlbnRyeSwgJnMuZW50cnlCdWZmZXIpCgoJZm9yIHsKCQlpZiBpbmRleCwgZXJyIDo9IHMuZW50cmllcy5QdXNoKHcpOyBlcnIgPT0gbmlsIHsKCQkJcy5oYXNobWFwW2hhc2hlZEtleV0gPSB1aW50NjQoaW5kZXgpCgkJCXMubG9jay5VbmxvY2soKQoJCQlyZXR1cm4gbmlsCgkJfQoJCWlmIHMucmVtb3ZlT2xkZXN0RW50cnkoTm9TcGFjZSkgIT0gbmlsIHsKCQkJcy5sb2NrLlVubG9jaygpCgkJCXJldHVybiBlcnJvcnMuTmV3KCJlbnRyeSBpcyBiaWdnZXIgdGhhbiBtYXggc2hhcmQgc2l6ZSIpCgkJfQoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBhZGROZXdXaXRob3V0TG9jayhrZXkgc3RyaW5nLCBoYXNoZWRLZXkgdWludDY0LCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWN1cnJlbnRUaW1lc3RhbXAgOj0gdWludDY0KHMuY2xvY2suRXBvY2goKSkKCglpZiAhcy5jbGVhbkVuYWJsZWQgewoJCWlmIG9sZGVzdEVudHJ5LCBlcnIgOj0gcy5lbnRyaWVzLlBlZWsoKTsgZXJyID09IG5pbCB7CgkJCXMub25FdmljdChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCwgcy5yZW1vdmVPbGRlc3RFbnRyeSkKCQl9Cgl9CgoJdyA6PSB3cmFwRW50cnkoY3VycmVudFRpbWVzdGFtcCwgaGFzaGVkS2V5LCBrZXksIGVudHJ5LCAmcy5lbnRyeUJ1ZmZlcikKCglmb3IgewoJCWlmIGluZGV4LCBlcnIgOj0gcy5lbnRyaWVzLlB1c2godyk7IGVyciA9PSBuaWwgewoJCQlzLmhhc2htYXBbaGFzaGVkS2V5XSA9IHVpbnQ2NChpbmRleCkKCQkJcmV0dXJuIG5pbAoJCX0KCQlpZiBzLnJlbW92ZU9sZGVzdEVudHJ5KE5vU3BhY2UpICE9IG5pbCB7CgkJCXJldHVybiBlcnJvcnMuTmV3KCJlbnRyeSBpcyBiaWdnZXIgdGhhbiBtYXggc2hhcmQgc2l6ZSIpCgkJfQoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBzZXRXcmFwcGVkRW50cnlXaXRob3V0TG9jayhjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgdyBbXWJ5dGUsIGhhc2hlZEtleSB1aW50NjQpIGVycm9yIHsKCWlmIHByZXZpb3VzSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV07IHByZXZpb3VzSW5kZXggIT0gMCB7CgkJaWYgcHJldmlvdXNFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KHByZXZpb3VzSW5kZXgpKTsgZXJyID09IG5pbCB7CgkJCXJlc2V0SGFzaEZyb21FbnRyeShwcmV2aW91c0VudHJ5KQoJCX0KCX0KCglpZiAhcy5jbGVhbkVuYWJsZWQgewoJCWlmIG9sZGVzdEVudHJ5LCBlcnIgOj0gcy5lbnRyaWVzLlBlZWsoKTsgZXJyID09IG5pbCB7CgkJCXMub25FdmljdChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCwgcy5yZW1vdmVPbGRlc3RFbnRyeSkKCQl9Cgl9CgoJZm9yIHsKCQlpZiBpbmRleCwgZXJyIDo9IHMuZW50cmllcy5QdXNoKHcpOyBlcnIgPT0gbmlsIHsKCQkJcy5oYXNobWFwW2hhc2hlZEtleV0gPSB1aW50NjQoaW5kZXgpCgkJCXJldHVybiBuaWwKCQl9CgkJaWYgcy5yZW1vdmVPbGRlc3RFbnRyeShOb1NwYWNlKSAhPSBuaWwgewoJCQlyZXR1cm4gZXJyb3JzLk5ldygiZW50cnkgaXMgYmlnZ2VyIHRoYW4gbWF4IHNoYXJkIHNpemUiKQoJCX0KCX0KfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgYXBwZW5kKGtleSBzdHJpbmcsIGhhc2hlZEtleSB1aW50NjQsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJcy5sb2NrLkxvY2soKQoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRWYWxpZFdyYXBFbnRyeShrZXksIGhhc2hlZEtleSkKCglpZiBlcnIgPT0gRXJyRW50cnlOb3RGb3VuZCB7CgkJZXJyID0gcy5hZGROZXdXaXRob3V0TG9jayhrZXksIGhhc2hlZEtleSwgZW50cnkpCgkJcy5sb2NrLlVubG9jaygpCgkJcmV0dXJuIGVycgoJfQoJaWYgZXJyICE9IG5pbCB7CgkJcy5sb2NrLlVubG9jaygpCgkJcmV0dXJuIGVycgoJfQoKCWN1cnJlbnRUaW1lc3RhbXAgOj0gdWludDY0KHMuY2xvY2suRXBvY2goKSkKCgl3IDo9IGFwcGVuZFRvV3JhcHBlZEVudHJ5KGN1cnJlbnRUaW1lc3RhbXAsIHdyYXBwZWRFbnRyeSwgZW50cnksICZzLmVudHJ5QnVmZmVyKQoKCWVyciA9IHMuc2V0V3JhcHBlZEVudHJ5V2l0aG91dExvY2soY3VycmVudFRpbWVzdGFtcCwgdywgaGFzaGVkS2V5KQoJcy5sb2NrLlVubG9jaygpCgoJcmV0dXJuIGVycgp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBkZWwoaGFzaGVkS2V5IHVpbnQ2NCkgZXJyb3IgewoJLy8gT3B0aW1pc3RpYyBwcmUtY2hlY2sgdXNpbmcgb25seSByZWFkbG9jawoJcy5sb2NrLlJMb2NrKCkKCXsKCQlpdGVtSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV0KCgkJaWYgaXRlbUluZGV4ID09IDAgewoJCQlzLmxvY2suUlVubG9jaygpCgkJCXMuZGVsbWlzcygpCgkJCXJldHVybiBFcnJFbnRyeU5vdEZvdW5kCgkJfQoKCQlpZiBlcnIgOj0gcy5lbnRyaWVzLkNoZWNrR2V0KGludChpdGVtSW5kZXgpKTsgZXJyICE9IG5pbCB7CgkJCXMubG9jay5SVW5sb2NrKCkKCQkJcy5kZWxtaXNzKCkKCQkJcmV0dXJuIGVycgoJCX0KCX0KCXMubG9jay5SVW5sb2NrKCkKCglzLmxvY2suTG9jaygpCgl7CgkJLy8gQWZ0ZXIgb2J0YWluaW5nIHRoZSB3cml0ZWxvY2ssIHdlIG5lZWQgdG8gcmVhZCB0aGUgc2FtZSBhZ2FpbiwKCQkvLyBzaW5jZSB0aGUgZGF0YSBkZWxpdmVyZWQgZWFybGllciBtYXkgYmUgc3RhbGUgbm93CgkJaXRlbUluZGV4IDo9IHMuaGFzaG1hcFtoYXNoZWRLZXldCgoJCWlmIGl0ZW1JbmRleCA9PSAwIHsKCQkJcy5sb2NrLlVubG9jaygpCgkJCXMuZGVsbWlzcygpCgkJCXJldHVybiBFcnJFbnRyeU5vdEZvdW5kCgkJfQoKCQl3cmFwcGVkRW50cnksIGVyciA6PSBzLmVudHJpZXMuR2V0KGludChpdGVtSW5kZXgpKQoJCWlmIGVyciAhPSBuaWwgewoJCQlzLmxvY2suVW5sb2NrKCkKCQkJcy5kZWxtaXNzKCkKCQkJcmV0dXJuIGVycgoJCX0KCgkJZGVsZXRlKHMuaGFzaG1hcCwgaGFzaGVkS2V5KQoJCXMub25SZW1vdmUod3JhcHBlZEVudHJ5LCBEZWxldGVkKQoJCWlmIHMuc3RhdHNFbmFibGVkIHsKCQkJZGVsZXRlKHMuaGFzaG1hcFN0YXRzLCBoYXNoZWRLZXkpCgkJfQoJCXJlc2V0SGFzaEZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgl9CglzLmxvY2suVW5sb2NrKCkKCglzLmRlbGhpdCgpCglyZXR1cm4gbmlsCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglpZiBzLmlzRXhwaXJlZChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCkgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBpc0V4cGlyZWQob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPD0gb2xkZXN0VGltZXN0YW1wIHsgLy8gaWYgY3VycmVudFRpbWVzdGFtcCA8IG9sZGVzdFRpbWVzdGFtcCwgdGhlIHJlc3VsdCB3aWxsIG91dCBvZiB1aW50NjQgbGltaXRzOwoJCXJldHVybiBmYWxzZQoJfQoJcmV0dXJuIGN1cnJlbnRUaW1lc3RhbXAtb2xkZXN0VGltZXN0YW1wID4gcy5saWZlV2luZG93Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGNsZWFuVXAoY3VycmVudFRpbWVzdGFtcCB1aW50NjQpIHsKCXMubG9jay5Mb2NrKCkKCWZvciB7CgkJaWYgb2xkZXN0RW50cnksIGVyciA6PSBzLmVudHJpZXMuUGVlaygpOyBlcnIgIT0gbmlsIHsKCQkJYnJlYWsKCQl9IGVsc2UgaWYgZXZpY3RlZCA6PSBzLm9uRXZpY3Qob2xkZXN0RW50cnksIGN1cnJlbnRUaW1lc3RhbXAsIHMucmVtb3ZlT2xkZXN0RW50cnkpOyAhZXZpY3RlZCB7CgkJCWJyZWFrCgkJfQoJfQoJcy5sb2NrLlVubG9jaygpCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldEVudHJ5KGhhc2hlZEtleSB1aW50NjQpIChbXWJ5dGUsIGVycm9yKSB7CglzLmxvY2suUkxvY2soKQoKCWVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJLy8gY29weSBlbnRyeQoJbmV3RW50cnkgOj0gbWFrZShbXWJ5dGUsIGxlbihlbnRyeSkpCgljb3B5KG5ld0VudHJ5LCBlbnRyeSkKCglzLmxvY2suUlVubG9jaygpCgoJcmV0dXJuIG5ld0VudHJ5LCBlcnIKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgY29weUhhc2hlZEtleXMoKSAoa2V5cyBbXXVpbnQ2NCwgbmV4dCBpbnQpIHsKCXMubG9jay5STG9jaygpCglrZXlzID0gbWFrZShbXXVpbnQ2NCwgbGVuKHMuaGFzaG1hcCkpCgoJZm9yIGtleSA6PSByYW5nZSBzLmhhc2htYXAgewoJCWtleXNbbmV4dF0gPSBrZXkKCQluZXh0KysKCX0KCglzLmxvY2suUlVubG9jaygpCglyZXR1cm4ga2V5cywgbmV4dAp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSByZW1vdmVPbGRlc3RFbnRyeShyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvciB7CglvbGRlc3QsIGVyciA6PSBzLmVudHJpZXMuUG9wKCkKCWlmIGVyciA9PSBuaWwgewoJCWhhc2ggOj0gcmVhZEhhc2hGcm9tRW50cnkob2xkZXN0KQoJCWlmIGhhc2ggPT0gMCB7CgkJCS8vIGVudHJ5IGhhcyBiZWVuIGV4cGxpY2l0bHkgZGVsZXRlZCB3aXRoIHJlc2V0SGFzaEZyb21FbnRyeSwgaWdub3JlCgkJCXJldHVybiBuaWwKCQl9CgkJZGVsZXRlKHMuaGFzaG1hcCwgaGFzaCkKCQlzLm9uUmVtb3ZlKG9sZGVzdCwgcmVhc29uKQoJCWlmIHMuc3RhdHNFbmFibGVkIHsKCQkJZGVsZXRlKHMuaGFzaG1hcFN0YXRzLCBoYXNoKQoJCX0KCQlyZXR1cm4gbmlsCgl9CglyZXR1cm4gZXJyCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIHJlc2V0KGNvbmZpZyBDb25maWcpIHsKCXMubG9jay5Mb2NrKCkKCXMuaGFzaG1hcCA9IG1ha2UobWFwW3VpbnQ2NF11aW50NjQsIGNvbmZpZy5pbml0aWFsU2hhcmRTaXplKCkpCglzLmVudHJ5QnVmZmVyID0gbWFrZShbXWJ5dGUsIGNvbmZpZy5NYXhFbnRyeVNpemUraGVhZGVyc1NpemVJbkJ5dGVzKQoJcy5lbnRyaWVzLlJlc2V0KCkKCXMubG9jay5VbmxvY2soKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSByZXNldFN0YXRzKCkgewoJcy5sb2NrLkxvY2soKQoJcy5zdGF0cyA9IFN0YXRze30KCXMubG9jay5VbmxvY2soKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBsZW4oKSBpbnQgewoJcy5sb2NrLlJMb2NrKCkKCXJlcyA6PSBsZW4ocy5oYXNobWFwKQoJcy5sb2NrLlJVbmxvY2soKQoJcmV0dXJuIHJlcwp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBjYXBhY2l0eSgpIGludCB7CglzLmxvY2suUkxvY2soKQoJcmVzIDo9IHMuZW50cmllcy5DYXBhY2l0eSgpCglzLmxvY2suUlVubG9jaygpCglyZXR1cm4gcmVzCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldFN0YXRzKCkgU3RhdHMgewoJdmFyIHN0YXRzID0gU3RhdHN7CgkJSGl0czogICAgICAgYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5IaXRzKSwKCQlNaXNzZXM6ICAgICBhdG9taWMuTG9hZEludDY0KCZzLnN0YXRzLk1pc3NlcyksCgkJRGVsSGl0czogICAgYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5EZWxIaXRzKSwKCQlEZWxNaXNzZXM6ICBhdG9taWMuTG9hZEludDY0KCZzLnN0YXRzLkRlbE1pc3NlcyksCgkJQ29sbGlzaW9uczogYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5Db2xsaXNpb25zKSwKCX0KCXJldHVybiBzdGF0cwp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBnZXRLZXlNZXRhZGF0YVdpdGhMb2NrKGtleSB1aW50NjQpIE1ldGFkYXRhIHsKCXMubG9jay5STG9jaygpCgljIDo9IHMuaGFzaG1hcFN0YXRzW2tleV0KCXMubG9jay5SVW5sb2NrKCkKCXJldHVybiBNZXRhZGF0YXsKCQlSZXF1ZXN0Q291bnQ6IGMsCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldEtleU1ldGFkYXRhKGtleSB1aW50NjQpIE1ldGFkYXRhIHsKCXJldHVybiBNZXRhZGF0YXsKCQlSZXF1ZXN0Q291bnQ6IHMuaGFzaG1hcFN0YXRzW2tleV0sCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGhpdChrZXkgdWludDY0KSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuSGl0cywgMSkKCWlmIHMuc3RhdHNFbmFibGVkIHsKCQlzLmxvY2suTG9jaygpCgkJcy5oYXNobWFwU3RhdHNba2V5XSsrCgkJcy5sb2NrLlVubG9jaygpCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGhpdFdpdGhvdXRMb2NrKGtleSB1aW50NjQpIHsKCWF0b21pYy5BZGRJbnQ2NCgmcy5zdGF0cy5IaXRzLCAxKQoJaWYgcy5zdGF0c0VuYWJsZWQgewoJCXMuaGFzaG1hcFN0YXRzW2tleV0rKwoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBtaXNzKCkgewoJYXRvbWljLkFkZEludDY0KCZzLnN0YXRzLk1pc3NlcywgMSkKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZGVsaGl0KCkgewoJYXRvbWljLkFkZEludDY0KCZzLnN0YXRzLkRlbEhpdHMsIDEpCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGRlbG1pc3MoKSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuRGVsTWlzc2VzLCAxKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBjb2xsaXNpb24oKSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuQ29sbGlzaW9ucywgMSkKfQoKZnVuYyBpbml0TmV3U2hhcmQoY29uZmlnIENvbmZpZywgY2FsbGJhY2sgb25SZW1vdmVDYWxsYmFjaywgY2xvY2sgY2xvY2spICpjYWNoZVNoYXJkIHsKCWJ5dGVzUXVldWVJbml0aWFsQ2FwYWNpdHkgOj0gY29uZmlnLmluaXRpYWxTaGFyZFNpemUoKSAqIGNvbmZpZy5NYXhFbnRyeVNpemUKCW1heGltdW1TaGFyZFNpemVJbkJ5dGVzIDo9IGNvbmZpZy5tYXhpbXVtU2hhcmRTaXplSW5CeXRlcygpCglpZiBtYXhpbXVtU2hhcmRTaXplSW5CeXRlcyA+IDAgJiYgYnl0ZXNRdWV1ZUluaXRpYWxDYXBhY2l0eSA+IG1heGltdW1TaGFyZFNpemVJbkJ5dGVzIHsKCQlieXRlc1F1ZXVlSW5pdGlhbENhcGFjaXR5ID0gbWF4aW11bVNoYXJkU2l6ZUluQnl0ZXMKCX0KCXJldHVybiAmY2FjaGVTaGFyZHsKCQloYXNobWFwOiAgICAgIG1ha2UobWFwW3VpbnQ2NF11aW50NjQsIGNvbmZpZy5pbml0aWFsU2hhcmRTaXplKCkpLAoJCWhhc2htYXBTdGF0czogbWFrZShtYXBbdWludDY0XXVpbnQzMiwgY29uZmlnLmluaXRpYWxTaGFyZFNpemUoKSksCgkJZW50cmllczogICAgICAqcXVldWUuTmV3Qnl0ZXNRdWV1ZShieXRlc1F1ZXVlSW5pdGlhbENhcGFjaXR5LCBtYXhpbXVtU2hhcmRTaXplSW5CeXRlcywgY29uZmlnLlZlcmJvc2UpLAoJCWVudHJ5QnVmZmVyOiAgbWFrZShbXWJ5dGUsIGNvbmZpZy5NYXhFbnRyeVNpemUraGVhZGVyc1NpemVJbkJ5dGVzKSwKCQlvblJlbW92ZTogICAgIGNhbGxiYWNrLAoKCQlpc1ZlcmJvc2U6ICAgIGNvbmZpZy5WZXJib3NlLAoJCWxvZ2dlcjogICAgICAgbmV3TG9nZ2VyKGNvbmZpZy5Mb2dnZXIpLAoJCWNsb2NrOiAgICAgICAgY2xvY2ssCgkJbGlmZVdpbmRvdzogICB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKSwKCQlzdGF0c0VuYWJsZWQ6IGNvbmZpZy5TdGF0c0VuYWJsZWQsCgkJY2xlYW5FbmFibGVkOiBjb25maWcuQ2xlYW5XaW5kb3cgPiAwLAoJfQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..022aac10960ea11a0c088f5db78594e4be4168e4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:a8eef514c69ad92ca25f5d49f615710e581e538c4f4d3d072ec9318314179fc9" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..90d17faf4e0d966473f2fa4062dffc715fe0ca11 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/manifest.json @@ -0,0 +1,231 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..ddb9db30f4bbf0c2afc906ef3f89207851df9435 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__v4fgmvqd/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "adcddf82c946fac328d37f92e0b6e980976ff2e21d2378b7fc120e939d2fa5fc", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..af894cb461ca73f212e5ed4cca0b33d5c54523c5 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength < len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes-keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e455537cad0a23c73382bfa17f1264611aeb09e2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/instruction.md @@ -0,0 +1,51 @@ +Cache entry encoding corrupted causing slice bounds out of range panics + +#### Description + +When storing entries in the cache, the encoding logic appears to be corrupted, leading to runtime panics with "slice bounds out of range" errors. This affects basic cache operations like setting and retrieving values. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + cache, _ := bigcache.NewBigCache(config) + + // This should work but causes a panic + err := cache.Set("testkey", []byte("testvalue")) + if err != nil { + fmt.Printf("Error setting key: %v\n", err) + return + } + + value, err := cache.Get("testkey") + if err != nil { + fmt.Printf("Error getting key: %v\n", err) + return + } + + fmt.Printf("Retrieved value: %s\n", string(value)) +} +``` + +The above code panics with: +``` +panic: runtime error: slice bounds out of range [:8388632] with capacity 518 +``` + +#### Expected Behavior + +Cache operations should work normally without panics. Setting a key-value pair and then retrieving it should return the original value. + +#### Actual Behavior + +The cache operations cause runtime panics due to slice bounds errors in the encoding logic, making the cache unusable for basic operations. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..59477c849aafbdbe6dbc34a6868812ca7f3dfec4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/provenance.json @@ -0,0 +1,372 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "encoding.go": { + "mode": "0o644", + "sha256": "fc2c5ef7610167b908fe97d4243eb6288b141db8a6d37e21677c997ff2901155", + "size": 2629 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 2, + "original_patch_sha256": "e5e32547736be8575fcdde780ac78e630a7f2db56661d7f3cc97b24f25e160ad", + "retained_mutation_file": "encoding.go", + "retained_mutation_hunk_sha256": "db4c0c3b0d950c4c77d371605941b94c65d2df41068f3f32e85a6b158b0f97b1" + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "78dc370eabe673a41951515a8e3694e015b1eb498573e40879be7f8e69770835", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "c95c7d4de9bb7ed23d67b147a957794aa5131019e976fd905578038b686d0aa7", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "4650050ced933f432781a1c472354e678c00a1eae148afef26bf283c4023027a", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "10eb2d72caef2808c6cb964be43ecf4e644671e75216786db4b5cb7d3681b0b9", + "is_fork": true, + "learner_path": "tasks/07ece388d1038050f69cd421/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/d82ff56abce4b9b4ed889ad00e133928f619a9b3/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "e5e32547736be8575fcdde780ac78e630a7f2db56661d7f3cc97b24f25e160ad", + "provenance_path": "tasks/07ece388d1038050f69cd421/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "d82ff56abce4b9b4ed889ad00e133928f619a9b3", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "cc69e8e9bde30f7feccca5415c461f389774ffec", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc", + "task_sha256": "09776cb39960a0220870ef9fe0448433d1167d899a1d54020958665cc53fdd05", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "3331a2f5b20cce3e510e44b0e34567e4f197b51248149db322ef65024f12bcb4", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..953d946ba0c37042296bedb9bb1ea64a497b8a10 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"encoding.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCikKCmNvbnN0ICgKCXRpbWVzdGFtcFNpemVJbkJ5dGVzID0gOCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgdGltZXN0YW1wCgloYXNoU2l6ZUluQnl0ZXMgICAgICA9IDggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLy8gTnVtYmVyIG9mIGJ5dGVzIHVzZWQgZm9yIGhhc2gKCWtleVNpemVJbkJ5dGVzICAgICAgID0gMiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3Igc2l6ZSBvZiBlbnRyeSBrZXkKCWhlYWRlcnNTaXplSW5CeXRlcyAgID0gdGltZXN0YW1wU2l6ZUluQnl0ZXMgKyBoYXNoU2l6ZUluQnl0ZXMgKyBrZXlTaXplSW5CeXRlcyAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgYWxsIGhlYWRlcnMKKQoKZnVuYyB3cmFwRW50cnkodGltZXN0YW1wIHVpbnQ2NCwgaGFzaCB1aW50NjQsIGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSwgYnVmZmVyICpbXWJ5dGUpIFtdYnl0ZSB7CglrZXlMZW5ndGggOj0gbGVuKGtleSkKCWJsb2JMZW5ndGggOj0gbGVuKGVudHJ5KSArIGhlYWRlcnNTaXplSW5CeXRlcyArIGtleUxlbmd0aAoKCWlmIGJsb2JMZW5ndGggPiBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCWJsb2IgOj0gKmJ1ZmZlcgoKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2IsIHRpbWVzdGFtcCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgaGFzaCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDE2KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0sIHVpbnQxNihrZXlMZW5ndGgpKQoJY29weShibG9iW2hlYWRlcnNTaXplSW5CeXRlczpdLCBrZXkpCgljb3B5KGJsb2JbaGVhZGVyc1NpemVJbkJ5dGVzK2tleUxlbmd0aDpdLCBlbnRyeSkKCglyZXR1cm4gYmxvYls6YmxvYkxlbmd0aF0KfQoKZnVuYyBhcHBlbmRUb1dyYXBwZWRFbnRyeSh0aW1lc3RhbXAgdWludDY0LCB3cmFwcGVkRW50cnkgW11ieXRlLCBlbnRyeSBbXWJ5dGUsIGJ1ZmZlciAqW11ieXRlKSBbXWJ5dGUgewoJYmxvYkxlbmd0aCA6PSBsZW4od3JhcHBlZEVudHJ5KSArIGxlbihlbnRyeSkKCWlmIGJsb2JMZW5ndGggPiBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCglibG9iIDo9ICpidWZmZXIKCgliaW5hcnkuTGl0dGxlRW5kaWFuLlB1dFVpbnQ2NChibG9iLCB0aW1lc3RhbXApCgljb3B5KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgd3JhcHBlZEVudHJ5W3RpbWVzdGFtcFNpemVJbkJ5dGVzOl0pCgljb3B5KGJsb2JbbGVuKHdyYXBwZWRFbnRyeSk6XSwgZW50cnkpCgoJcmV0dXJuIGJsb2JbOmJsb2JMZW5ndGhdCn0KCmZ1bmMgcmVhZEVudHJ5KGRhdGEgW11ieXRlKSBbXWJ5dGUgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbihkYXRhKS1pbnQoaGVhZGVyc1NpemVJbkJ5dGVzK2xlbmd0aCkpCgljb3B5KGRzdCwgZGF0YVtoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoOl0pCgoJcmV0dXJuIGRzdAp9CgpmdW5jIHJlYWRUaW1lc3RhbXBGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YSkKfQoKZnVuYyByZWFkS2V5RnJvbUVudHJ5KGRhdGEgW11ieXRlKSBzdHJpbmcgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbmd0aCkKCWNvcHkoZHN0LCBkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkc3QpCn0KCmZ1bmMgY29tcGFyZUtleUZyb21FbnRyeShkYXRhIFtdYnl0ZSwga2V5IHN0cmluZykgYm9vbCB7CglsZW5ndGggOj0gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50MTYoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlcytoYXNoU2l6ZUluQnl0ZXM6XSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkgPT0ga2V5Cn0KCmZ1bmMgcmVhZEhhc2hGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdKQp9CgpmdW5jIHJlc2V0SGFzaEZyb21FbnRyeShkYXRhIFtdYnl0ZSkgewoJYmluYXJ5LkxpdHRsZUVuZGlhbi5QdXRVaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdLCAwKQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..773269bbe743dfe717cc9ff006610c63c22b5334 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:fa37f9d29dd2ab10fcaeb693ebf23ebdc6574597458a82a54f8a8fcdf29f143e" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..2715d3c85965a1e6193d210cac2e2090a55741b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/manifest.json @@ -0,0 +1,256 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/partial-repair.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..4dcd0914e75809a03cf39a64a78675945e19e820 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"encoding.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCikKCmNvbnN0ICgKCXRpbWVzdGFtcFNpemVJbkJ5dGVzID0gOCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgdGltZXN0YW1wCgloYXNoU2l6ZUluQnl0ZXMgICAgICA9IDggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLy8gTnVtYmVyIG9mIGJ5dGVzIHVzZWQgZm9yIGhhc2gKCWtleVNpemVJbkJ5dGVzICAgICAgID0gMiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3Igc2l6ZSBvZiBlbnRyeSBrZXkKCWhlYWRlcnNTaXplSW5CeXRlcyAgID0gdGltZXN0YW1wU2l6ZUluQnl0ZXMgKyBoYXNoU2l6ZUluQnl0ZXMgKyBrZXlTaXplSW5CeXRlcyAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgYWxsIGhlYWRlcnMKKQoKZnVuYyB3cmFwRW50cnkodGltZXN0YW1wIHVpbnQ2NCwgaGFzaCB1aW50NjQsIGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSwgYnVmZmVyICpbXWJ5dGUpIFtdYnl0ZSB7CglrZXlMZW5ndGggOj0gbGVuKGtleSkKCWJsb2JMZW5ndGggOj0gbGVuKGVudHJ5KSArIGhlYWRlcnNTaXplSW5CeXRlcyArIGtleUxlbmd0aAoKCWlmIGJsb2JMZW5ndGggPCBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCWJsb2IgOj0gKmJ1ZmZlcgoKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2IsIHRpbWVzdGFtcCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgaGFzaCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDE2KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0sIHVpbnQxNihrZXlMZW5ndGgpKQoJY29weShibG9iW2hlYWRlcnNTaXplSW5CeXRlczpdLCBrZXkpCgljb3B5KGJsb2JbaGVhZGVyc1NpemVJbkJ5dGVzK2tleUxlbmd0aDpdLCBlbnRyeSkKCglyZXR1cm4gYmxvYls6YmxvYkxlbmd0aF0KfQoKZnVuYyBhcHBlbmRUb1dyYXBwZWRFbnRyeSh0aW1lc3RhbXAgdWludDY0LCB3cmFwcGVkRW50cnkgW11ieXRlLCBlbnRyeSBbXWJ5dGUsIGJ1ZmZlciAqW11ieXRlKSBbXWJ5dGUgewoJYmxvYkxlbmd0aCA6PSBsZW4od3JhcHBlZEVudHJ5KSArIGxlbihlbnRyeSkKCWlmIGJsb2JMZW5ndGggPiBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCglibG9iIDo9ICpidWZmZXIKCgliaW5hcnkuTGl0dGxlRW5kaWFuLlB1dFVpbnQ2NChibG9iLCB0aW1lc3RhbXApCgljb3B5KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgd3JhcHBlZEVudHJ5W3RpbWVzdGFtcFNpemVJbkJ5dGVzOl0pCgljb3B5KGJsb2JbbGVuKHdyYXBwZWRFbnRyeSk6XSwgZW50cnkpCgoJcmV0dXJuIGJsb2JbOmJsb2JMZW5ndGhdCn0KCmZ1bmMgcmVhZEVudHJ5KGRhdGEgW11ieXRlKSBbXWJ5dGUgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbihkYXRhKS1pbnQoaGVhZGVyc1NpemVJbkJ5dGVzK2xlbmd0aCkpCgljb3B5KGRzdCwgZGF0YVtoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoOl0pCgoJcmV0dXJuIGRzdAp9CgpmdW5jIHJlYWRUaW1lc3RhbXBGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YSkKfQoKZnVuYyByZWFkS2V5RnJvbUVudHJ5KGRhdGEgW11ieXRlKSBzdHJpbmcgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbmd0aCkKCWNvcHkoZHN0LCBkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkc3QpCn0KCmZ1bmMgY29tcGFyZUtleUZyb21FbnRyeShkYXRhIFtdYnl0ZSwga2V5IHN0cmluZykgYm9vbCB7CglsZW5ndGggOj0gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50MTYoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlcytoYXNoU2l6ZUluQnl0ZXM6XSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkgPT0ga2V5Cn0KCmZ1bmMgcmVhZEhhc2hGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdKQp9CgpmdW5jIHJlc2V0SGFzaEZyb21FbnRyeShkYXRhIFtdYnl0ZSkgewoJYmluYXJ5LkxpdHRsZUVuZGlhbi5QdXRVaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdLCAwKQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2174da0d5be0ae335d7e77b358fd5a3157c1f6d8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_flip_operators__wvhqy0fc/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "874da3a93c7790bb012806bc1e68d9ee797457951d05f2ef88fe0bd02134b5e8", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..c7f91dfe1461ee0255959bf05ba90ee1589920fa --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i != it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount >= 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d058606bc7c5b917f88d3394315308300089aede --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/instruction.md @@ -0,0 +1,60 @@ +Iterator panics with index out of range when iterating over cache with empty shards + +#### Description + +The EntryInfoIterator panics with "index out of range [0] with length 0" when iterating over a cache that has empty shards during concurrent operations. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "sync" + "time" + + "github.com/allegro/bigcache/v3" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + config.Shards = 4 + cache, _ := bigcache.New(context.Background(), config) + + var wg sync.WaitGroup + + // Add some entries concurrently + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte(fmt.Sprintf("value%d", i))) + time.Sleep(time.Millisecond) + } + }() + + // Iterate while adding entries + wg.Add(1) + go func() { + defer wg.Done() + time.Sleep(50 * time.Millisecond) // Let some entries be added first + + iterator := cache.Iterator() + for iterator.SetNext() { + entry, _ := iterator.Value() + fmt.Printf("Key: %s\n", entry.Key()) + } + }() + + wg.Wait() +} +``` + +This code will panic with: +``` +panic: runtime error: index out of range [0] with length 0 +``` + +The issue occurs when the iterator encounters shards that become empty during iteration, particularly in concurrent scenarios where entries are being added while iterating. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..ccffcb724e2013743907baa1b8a691480cfd63e8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "a003884f119b0a0218e67ab244c401b8753e23de970ea2f4e45c03c9a081bb5d", + "size": 3234 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "db826628bbaee3ef0d2b18deef5ac12795496b58373b71c5428041cacb4e795c", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "57048ec6f87a0fab0d66e9a75e2daf42aaedbcdbe69c1ca804093f2d1fe03c84", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "fbcdd5933dc5d8046f86f184373fbf05a47a84b2bd59133064f6c6de8f981d24", + "is_fork": true, + "learner_path": "tasks/b492b035ce4f48847291d36c/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/d72fec242a59d0c549b010312d1ead2a68be16bc/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "3feb962d57e39fe48da5559bee641f5f3239e3ac4a849985719272ba791273fc", + "provenance_path": "tasks/b492b035ce4f48847291d36c/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "d72fec242a59d0c549b010312d1ead2a68be16bc", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "b81583f8b95c8d1f8278b29147826291282ffc6a", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr", + "task_sha256": "5b6f1f964fae4b150088f568dbce7ca6177e13fc03c71849a075bec0295d06a9", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "21d0f0de737b8349cfd2f33c400413bfb8077361505e1cebbe67b6c4c1bfc516", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7953c2f5e16c548afb5dfc60d3b6b2926811fdbc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"iterator.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJzeW5jIgopCgp0eXBlIGl0ZXJhdG9yRXJyb3Igc3RyaW5nCgpmdW5jIChlIGl0ZXJhdG9yRXJyb3IpIEVycm9yKCkgc3RyaW5nIHsKCXJldHVybiBzdHJpbmcoZSkKfQoKLy8gRXJySW52YWxpZEl0ZXJhdG9yU3RhdGUgaXMgcmVwb3J0ZWQgd2hlbiBpdGVyYXRvciBpcyBpbiBpbnZhbGlkIHN0YXRlCmNvbnN0IEVyckludmFsaWRJdGVyYXRvclN0YXRlID0gaXRlcmF0b3JFcnJvcigiSXRlcmF0b3IgaXMgaW4gaW52YWxpZCBzdGF0ZS4gVXNlIFNldE5leHQoKSB0byBtb3ZlIHRvIG5leHQgcG9zaXRpb24iKQoKLy8gRXJyQ2Fubm90UmV0cmlldmVFbnRyeSBpcyByZXBvcnRlZCB3aGVuIGVudHJ5IGNhbm5vdCBiZSByZXRyaWV2ZWQgZnJvbSB1bmRlcmx5aW5nCmNvbnN0IEVyckNhbm5vdFJldHJpZXZlRW50cnkgPSBpdGVyYXRvckVycm9yKCJDb3VsZCBub3QgcmV0cmlldmUgZW50cnkgZnJvbSBjYWNoZSIpCgp2YXIgZW1wdHlFbnRyeUluZm8gPSBFbnRyeUluZm97fQoKLy8gRW50cnlJbmZvIGhvbGRzIGluZm9ybWF0aW9ucyBhYm91dCBlbnRyeSBpbiB0aGUgY2FjaGUKdHlwZSBFbnRyeUluZm8gc3RydWN0IHsKCXRpbWVzdGFtcCB1aW50NjQKCWhhc2ggICAgICB1aW50NjQKCWtleSAgICAgICBzdHJpbmcKCXZhbHVlICAgICBbXWJ5dGUKCWVyciAgICAgICBlcnJvcgp9CgovLyBLZXkgcmV0dXJucyBlbnRyeSdzIHVuZGVybHlpbmcga2V5CmZ1bmMgKGUgRW50cnlJbmZvKSBLZXkoKSBzdHJpbmcgewoJcmV0dXJuIGUua2V5Cn0KCi8vIEhhc2ggcmV0dXJucyBlbnRyeSdzIGhhc2ggdmFsdWUKZnVuYyAoZSBFbnRyeUluZm8pIEhhc2goKSB1aW50NjQgewoJcmV0dXJuIGUuaGFzaAp9CgovLyBUaW1lc3RhbXAgcmV0dXJucyBlbnRyeSdzIHRpbWVzdGFtcCAodGltZSBvZiBpbnNlcnRpb24pCmZ1bmMgKGUgRW50cnlJbmZvKSBUaW1lc3RhbXAoKSB1aW50NjQgewoJcmV0dXJuIGUudGltZXN0YW1wCn0KCi8vIFZhbHVlIHJldHVybnMgZW50cnkncyB1bmRlcmx5aW5nIHZhbHVlCmZ1bmMgKGUgRW50cnlJbmZvKSBWYWx1ZSgpIFtdYnl0ZSB7CglyZXR1cm4gZS52YWx1ZQp9CgovLyBFbnRyeUluZm9JdGVyYXRvciBhbGxvd3MgdG8gaXRlcmF0ZSBvdmVyIGVudHJpZXMgaW4gdGhlIGNhY2hlCnR5cGUgRW50cnlJbmZvSXRlcmF0b3Igc3RydWN0IHsKCW11dGV4ICAgICAgICAgICAgc3luYy5NdXRleAoJY2FjaGUgICAgICAgICAgICAqQmlnQ2FjaGUKCWN1cnJlbnRTaGFyZCAgICAgaW50CgljdXJyZW50SW5kZXggICAgIGludAoJY3VycmVudEVudHJ5SW5mbyBFbnRyeUluZm8KCWVsZW1lbnRzICAgICAgICAgW111aW50NjQKCWVsZW1lbnRzQ291bnQgICAgaW50Cgl2YWxpZCAgICAgICAgICAgIGJvb2wKfQoKLy8gU2V0TmV4dCBtb3ZlcyB0byBuZXh0IGVsZW1lbnQgYW5kIHJldHVybnMgdHJ1ZSBpZiBpdCBleGlzdHMuCmZ1bmMgKGl0ICpFbnRyeUluZm9JdGVyYXRvcikgU2V0TmV4dCgpIGJvb2wgewoJaXQubXV0ZXguTG9jaygpCgoJaXQudmFsaWQgPSBmYWxzZQoJaXQuY3VycmVudEluZGV4KysKCglpZiBpdC5lbGVtZW50c0NvdW50ID4gaXQuY3VycmVudEluZGV4IHsKCQlpdC52YWxpZCA9IHRydWUKCgkJZW1wdHkgOj0gaXQuc2V0Q3VycmVudEVudHJ5KCkKCQlpdC5tdXRleC5VbmxvY2soKQoKCQlpZiBlbXB0eSB7CgkJCXJldHVybiBpdC5TZXROZXh0KCkKCQl9CgkJcmV0dXJuIHRydWUKCX0KCglmb3IgaSA6PSBpdC5jdXJyZW50U2hhcmQgKyAxOyBpIDwgaXQuY2FjaGUuY29uZmlnLlNoYXJkczsgaSsrIHsKCQlpdC5lbGVtZW50cywgaXQuZWxlbWVudHNDb3VudCA9IGl0LmNhY2hlLnNoYXJkc1tpXS5jb3B5SGFzaGVkS2V5cygpCgoJCS8vIE5vbiBlbXB0eSBzaGFyZCAtIHN0aWNrIHdpdGggaXQKCQlpZiBpdC5lbGVtZW50c0NvdW50ID4gMCB7CgkJCWl0LmN1cnJlbnRJbmRleCA9IDAKCQkJaXQuY3VycmVudFNoYXJkID0gaQoJCQlpdC52YWxpZCA9IHRydWUKCgkJCWVtcHR5IDo9IGl0LnNldEN1cnJlbnRFbnRyeSgpCgkJCWl0Lm11dGV4LlVubG9jaygpCgoJCQlpZiBlbXB0eSB7CgkJCQlyZXR1cm4gaXQuU2V0TmV4dCgpCgkJCX0KCQkJcmV0dXJuIHRydWUKCQl9Cgl9CglpdC5tdXRleC5VbmxvY2soKQoJcmV0dXJuIGZhbHNlCn0KCmZ1bmMgKGl0ICpFbnRyeUluZm9JdGVyYXRvcikgc2V0Q3VycmVudEVudHJ5KCkgYm9vbCB7Cgl2YXIgZW50cnlOb3RGb3VuZCA9IGZhbHNlCgllbnRyeSwgZXJyIDo9IGl0LmNhY2hlLnNoYXJkc1tpdC5jdXJyZW50U2hhcmRdLmdldEVudHJ5KGl0LmVsZW1lbnRzW2l0LmN1cnJlbnRJbmRleF0pCgoJaWYgZXJyID09IEVyckVudHJ5Tm90Rm91bmQgewoJCWl0LmN1cnJlbnRFbnRyeUluZm8gPSBlbXB0eUVudHJ5SW5mbwoJCWVudHJ5Tm90Rm91bmQgPSB0cnVlCgl9IGVsc2UgaWYgZXJyICE9IG5pbCB7CgkJaXQuY3VycmVudEVudHJ5SW5mbyA9IEVudHJ5SW5mb3sKCQkJZXJyOiBlcnIsCgkJfQoJfSBlbHNlIHsKCQlpdC5jdXJyZW50RW50cnlJbmZvID0gRW50cnlJbmZvewoJCQl0aW1lc3RhbXA6IHJlYWRUaW1lc3RhbXBGcm9tRW50cnkoZW50cnkpLAoJCQloYXNoOiAgICAgIHJlYWRIYXNoRnJvbUVudHJ5KGVudHJ5KSwKCQkJa2V5OiAgICAgICByZWFkS2V5RnJvbUVudHJ5KGVudHJ5KSwKCQkJdmFsdWU6ICAgICByZWFkRW50cnkoZW50cnkpLAoJCQllcnI6ICAgICAgIGVyciwKCQl9Cgl9CgoJcmV0dXJuIGVudHJ5Tm90Rm91bmQKfQoKZnVuYyBuZXdJdGVyYXRvcihjYWNoZSAqQmlnQ2FjaGUpICpFbnRyeUluZm9JdGVyYXRvciB7CgllbGVtZW50cywgY291bnQgOj0gY2FjaGUuc2hhcmRzWzBdLmNvcHlIYXNoZWRLZXlzKCkKCglyZXR1cm4gJkVudHJ5SW5mb0l0ZXJhdG9yewoJCWNhY2hlOiAgICAgICAgIGNhY2hlLAoJCWN1cnJlbnRTaGFyZDogIDAsCgkJY3VycmVudEluZGV4OiAgLTEsCgkJZWxlbWVudHM6ICAgICAgZWxlbWVudHMsCgkJZWxlbWVudHNDb3VudDogY291bnQsCgl9Cn0KCi8vIFZhbHVlIHJldHVybnMgY3VycmVudCB2YWx1ZSBmcm9tIHRoZSBpdGVyYXRvcgpmdW5jIChpdCAqRW50cnlJbmZvSXRlcmF0b3IpIFZhbHVlKCkgKEVudHJ5SW5mbywgZXJyb3IpIHsKCWlmICFpdC52YWxpZCB7CgkJcmV0dXJuIGVtcHR5RW50cnlJbmZvLCBFcnJJbnZhbGlkSXRlcmF0b3JTdGF0ZQoJfQoKCXJldHVybiBpdC5jdXJyZW50RW50cnlJbmZvLCBpdC5jdXJyZW50RW50cnlJbmZvLmVycgp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c94d685930b8d43ee9ccee7667a336d150fc08b5 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:532dae312f7b4868a49083a7305b5d10342f871dc9f5ee5f51a133ff0b78117f" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..420494cffe12452fd113f2f8c0c010cb74de7187 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/manifest.json @@ -0,0 +1,296 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..49a3fee9f7b863fac3c3a8a2e80b91cd8355d7bf --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__d2tu3dcr/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "3f6ce7179344c9045870f4d4f6abb8731cc120f3dc584d71d65f756eada899bb", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..83313a13a2f78e146c1f035aef133ce74277fe1e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail < q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head*q.tail != need*minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8c79d593e2aeee559bc2e0dc1bd6be4593e3efc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/instruction.md @@ -0,0 +1,37 @@ +BytesQueue canInsertAfterTail logic broken causing slice bounds out of range panics + +#### Description + +The `canInsertAfterTail` method in BytesQueue has incorrect logic that causes slice bounds out of range panics during queue operations. The condition check appears to be inverted and the calculation for available space is wrong. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + cache, _ := bigcache.NewBigCache(config) + + // This will eventually panic with slice bounds out of range + for i := 0; i < 1000; i++ { + key := fmt.Sprintf("key%d", i) + value := make([]byte, 400) // Large enough value + cache.Set(key, value) + } +} +``` + +The panic occurs with messages like: +``` +panic: runtime error: slice bounds out of range [:1054] with capacity 100 +panic: runtime error: slice bounds out of range [:212] with capacity 200 +``` + +This happens when the queue tries to insert data but the bounds checking logic is incorrect, leading to attempts to access memory beyond the allocated capacity. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..35157bd37566316bcc90c396f572be69bbbbc3c5 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "fac463482fc7edf7027a0b7eb9f498c7339990b19b7776122ed5b636ca18f048", + "size": 6855 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "58ea5ea5ec567d85b36c2f4a5b92a9f63c7c63b388e68f9a86239ab768651cf6", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "3eeca793189944578b7d80be6fbfb2174d6c854761514827d3b9c5f398c86464", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "fb8dda3adef2580a732ca2b9a8a59f698848fe8ad974256405954edd82ef81ce", + "is_fork": true, + "learner_path": "tasks/a8a1a38f789a9cf69c1247d1/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/678e5f534d05aef1ce9dbfd13b9fac5a016bec1a/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "c1c2a41135de5e07396b2ff6815c86ab73d12d5808160df39216f0508e407014", + "provenance_path": "tasks/a8a1a38f789a9cf69c1247d1/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "678e5f534d05aef1ce9dbfd13b9fac5a016bec1a", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "325dc1ec52bbdcfd6fb49c00eeef2bdd1da4d15c", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43", + "task_sha256": "793629cb218fe28ace8061d6bf7e95affb74e0b5d5ab305846d414387b67d410", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "88f354026f49f539b26332a1ba920f5d6d2881b80626c5d240de79ece1285906", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e4f032645f70e7b7e425953ed99476d657d7ce3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"queue/bytes_queue.go": {"data": "cGFja2FnZSBxdWV1ZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCgkibG9nIgoJInRpbWUiCikKCmNvbnN0ICgKCS8vIE51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgMCBpbiB1dmFyaW50IGZvcm1hdAoJbWluaW11bUhlYWRlclNpemUgPSAxNyAvLyAxIGJ5dGUgYmxvYnNpemUgKyB0aW1lc3RhbXBTaXplSW5CeXRlcyArIGhhc2hTaXplSW5CeXRlcwoJLy8gQnl0ZXMgYmVmb3JlIGxlZnQgbWFyZ2luIGFyZSBub3QgdXNlZC4gWmVybyBpbmRleCBtZWFucyBlbGVtZW50IGRvZXMgbm90IGV4aXN0IGluIHF1ZXVlLCB1c2VmdWwgd2hpbGUgcmVhZGluZyBzbGljZSBmcm9tIGluZGV4CglsZWZ0TWFyZ2luSW5kZXggPSAxCikKCnZhciAoCgllcnJFbXB0eVF1ZXVlICAgICAgID0gJnF1ZXVlRXJyb3J7IkVtcHR5IHF1ZXVlIn0KCWVyckludmFsaWRJbmRleCAgICAgPSAmcXVldWVFcnJvcnsiSW5kZXggbXVzdCBiZSBncmVhdGVyIHRoYW4gemVyby4gSW52YWxpZCBpbmRleC4ifQoJZXJySW5kZXhPdXRPZkJvdW5kcyA9ICZxdWV1ZUVycm9yeyJJbmRleCBvdXQgb2YgcmFuZ2UifQopCgovLyBCeXRlc1F1ZXVlIGlzIGEgbm9uLXRocmVhZCBzYWZlIHF1ZXVlIHR5cGUgb2YgZmlmbyBiYXNlZCBvbiBieXRlcyBhcnJheS4KLy8gRm9yIGV2ZXJ5IHB1c2ggb3BlcmF0aW9uIGluZGV4IG9mIGVudHJ5IGlzIHJldHVybmVkLiBJdCBjYW4gYmUgdXNlZCB0byByZWFkIHRoZSBlbnRyeSBsYXRlcgp0eXBlIEJ5dGVzUXVldWUgc3RydWN0IHsKCWZ1bGwgICAgICAgICBib29sCglhcnJheSAgICAgICAgW11ieXRlCgljYXBhY2l0eSAgICAgaW50CgltYXhDYXBhY2l0eSAgaW50CgloZWFkICAgICAgICAgaW50Cgl0YWlsICAgICAgICAgaW50Cgljb3VudCAgICAgICAgaW50CglyaWdodE1hcmdpbiAgaW50CgloZWFkZXJCdWZmZXIgW11ieXRlCgl2ZXJib3NlICAgICAgYm9vbAp9Cgp0eXBlIHF1ZXVlRXJyb3Igc3RydWN0IHsKCW1lc3NhZ2Ugc3RyaW5nCn0KCi8vIGdldE5lZWRlZFNpemUgcmV0dXJucyB0aGUgbnVtYmVyIG9mIGJ5dGVzIGFuIGVudHJ5IG9mIGxlbmd0aCBuZWVkIGluIHRoZSBxdWV1ZQpmdW5jIGdldE5lZWRlZFNpemUobGVuZ3RoIGludCkgaW50IHsKCXZhciBoZWFkZXIgaW50Cglzd2l0Y2ggewoJY2FzZSBsZW5ndGggPCAxMjc6IC8vIDE8PDctMQoJCWhlYWRlciA9IDEKCWNhc2UgbGVuZ3RoIDwgMTYzODI6IC8vIDE8PDE0LTIKCQloZWFkZXIgPSAyCgljYXNlIGxlbmd0aCA8IDIwOTcxNDk6IC8vIDE8PDIxIC0zCgkJaGVhZGVyID0gMwoJY2FzZSBsZW5ndGggPCAyNjg0MzU0NTI6IC8vIDE8PDI4IC00CgkJaGVhZGVyID0gNAoJZGVmYXVsdDoKCQloZWFkZXIgPSA1Cgl9CgoJcmV0dXJuIGxlbmd0aCArIGhlYWRlcgp9CgovLyBOZXdCeXRlc1F1ZXVlIGluaXRpYWxpemUgbmV3IGJ5dGVzIHF1ZXVlLgovLyBjYXBhY2l0eSBpcyB1c2VkIGluIGJ5dGVzIGFycmF5IGFsbG9jYXRpb24KLy8gV2hlbiB2ZXJib3NlIGZsYWcgaXMgc2V0IHRoZW4gaW5mb3JtYXRpb24gYWJvdXQgbWVtb3J5IGFsbG9jYXRpb24gYXJlIHByaW50ZWQKZnVuYyBOZXdCeXRlc1F1ZXVlKGNhcGFjaXR5IGludCwgbWF4Q2FwYWNpdHkgaW50LCB2ZXJib3NlIGJvb2wpICpCeXRlc1F1ZXVlIHsKCXJldHVybiAmQnl0ZXNRdWV1ZXsKCQlhcnJheTogICAgICAgIG1ha2UoW11ieXRlLCBjYXBhY2l0eSksCgkJY2FwYWNpdHk6ICAgICBjYXBhY2l0eSwKCQltYXhDYXBhY2l0eTogIG1heENhcGFjaXR5LAoJCWhlYWRlckJ1ZmZlcjogbWFrZShbXWJ5dGUsIGJpbmFyeS5NYXhWYXJpbnRMZW4zMiksCgkJdGFpbDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJaGVhZDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJcmlnaHRNYXJnaW46ICBsZWZ0TWFyZ2luSW5kZXgsCgkJdmVyYm9zZTogICAgICB2ZXJib3NlLAoJfQp9CgovLyBSZXNldCByZW1vdmVzIGFsbCBlbnRyaWVzIGZyb20gcXVldWUKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgUmVzZXQoKSB7CgkvLyBKdXN0IHJlc2V0IGluZGV4ZXMKCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJcS5oZWFkID0gbGVmdE1hcmdpbkluZGV4CglxLnJpZ2h0TWFyZ2luID0gbGVmdE1hcmdpbkluZGV4CglxLmNvdW50ID0gMAoJcS5mdWxsID0gZmFsc2UKfQoKLy8gUHVzaCBjb3BpZXMgZW50cnkgYXQgdGhlIGVuZCBvZiBxdWV1ZSBhbmQgbW92ZXMgdGFpbCBwb2ludGVyLiBBbGxvY2F0ZXMgbW9yZSBzcGFjZSBpZiBuZWVkZWQuCi8vIFJldHVybnMgaW5kZXggZm9yIHB1c2hlZCBkYXRhIG9yIGVycm9yIGlmIG1heGltdW0gc2l6ZSBxdWV1ZSBsaW1pdCBpcyByZWFjaGVkLgpmdW5jIChxICpCeXRlc1F1ZXVlKSBQdXNoKGRhdGEgW11ieXRlKSAoaW50LCBlcnJvcikgewoJbmVlZGVkU2l6ZSA6PSBnZXROZWVkZWRTaXplKGxlbihkYXRhKSkKCglpZiAhcS5jYW5JbnNlcnRBZnRlclRhaWwobmVlZGVkU2l6ZSkgewoJCWlmIHEuY2FuSW5zZXJ0QmVmb3JlSGVhZChuZWVkZWRTaXplKSB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0gZWxzZSBpZiBxLmNhcGFjaXR5K25lZWRlZFNpemUgPj0gcS5tYXhDYXBhY2l0eSAmJiBxLm1heENhcGFjaXR5ID4gMCB7CgkJCXJldHVybiAtMSwgJnF1ZXVlRXJyb3J7IkZ1bGwgcXVldWUuIE1heGltdW0gc2l6ZSBsaW1pdCByZWFjaGVkLiJ9CgkJfSBlbHNlIHsKCQkJcS5hbGxvY2F0ZUFkZGl0aW9uYWxNZW1vcnkobmVlZGVkU2l6ZSkKCQl9Cgl9CgoJaW5kZXggOj0gcS50YWlsCgoJcS5wdXNoKGRhdGEsIG5lZWRlZFNpemUpCgoJcmV0dXJuIGluZGV4LCBuaWwKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgYWxsb2NhdGVBZGRpdGlvbmFsTWVtb3J5KG1pbmltdW0gaW50KSB7CglzdGFydCA6PSB0aW1lLk5vdygpCglpZiBxLmNhcGFjaXR5IDwgbWluaW11bSB7CgkJcS5jYXBhY2l0eSArPSBtaW5pbXVtCgl9CglxLmNhcGFjaXR5ID0gcS5jYXBhY2l0eSAqIDIKCWlmIHEuY2FwYWNpdHkgPiBxLm1heENhcGFjaXR5ICYmIHEubWF4Q2FwYWNpdHkgPiAwIHsKCQlxLmNhcGFjaXR5ID0gcS5tYXhDYXBhY2l0eQoJfQoKCW9sZEFycmF5IDo9IHEuYXJyYXkKCXEuYXJyYXkgPSBtYWtlKFtdYnl0ZSwgcS5jYXBhY2l0eSkKCglpZiBsZWZ0TWFyZ2luSW5kZXggIT0gcS5yaWdodE1hcmdpbiB7CgkJY29weShxLmFycmF5LCBvbGRBcnJheVs6cS5yaWdodE1hcmdpbl0pCgoJCWlmIHEudGFpbCA8PSBxLmhlYWQgewoJCQlpZiBxLnRhaWwgIT0gcS5oZWFkIHsKCQkJCS8vIGNyZWF0ZWQgc2xpY2UgaXMgc2xpZ2h0bHkgbGFyZ2VyIHRoYW4gbmVlZCBidXQgdGhpcyBpcyBmaW5lIGFmdGVyIG9ubHkgdGhlIG5lZWRlZCBieXRlcyBhcmUgY29waWVkCgkJCQlxLnB1c2gobWFrZShbXWJ5dGUsIHEuaGVhZC1xLnRhaWwpLCBxLmhlYWQtcS50YWlsKQoJCQl9CgoJCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQkJcS50YWlsID0gcS5yaWdodE1hcmdpbgoJCX0KCX0KCglxLmZ1bGwgPSBmYWxzZQoKCWlmIHEudmVyYm9zZSB7CgkJbG9nLlByaW50ZigiQWxsb2NhdGVkIG5ldyBxdWV1ZSBpbiAlczsgQ2FwYWNpdHk6ICVkIFxuIiwgdGltZS5TaW5jZShzdGFydCksIHEuY2FwYWNpdHkpCgl9Cn0KCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIHB1c2goZGF0YSBbXWJ5dGUsIGxlbiBpbnQpIHsKCWhlYWRlckVudHJ5U2l6ZSA6PSBiaW5hcnkuUHV0VXZhcmludChxLmhlYWRlckJ1ZmZlciwgdWludDY0KGxlbikpCglxLmNvcHkocS5oZWFkZXJCdWZmZXIsIGhlYWRlckVudHJ5U2l6ZSkKCglxLmNvcHkoZGF0YSwgbGVuLWhlYWRlckVudHJ5U2l6ZSkKCglpZiBxLnRhaWwgPiBxLmhlYWQgewoJCXEucmlnaHRNYXJnaW4gPSBxLnRhaWwKCX0KCWlmIHEudGFpbCA9PSBxLmhlYWQgewoJCXEuZnVsbCA9IHRydWUKCX0KCglxLmNvdW50KysKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgY29weShkYXRhIFtdYnl0ZSwgbGVuIGludCkgewoJcS50YWlsICs9IGNvcHkocS5hcnJheVtxLnRhaWw6XSwgZGF0YVs6bGVuXSkKfQoKLy8gUG9wIHJlYWRzIHRoZSBvbGRlc3QgZW50cnkgZnJvbSBxdWV1ZSBhbmQgbW92ZXMgaGVhZCBwb2ludGVyIHRvIHRoZSBuZXh0IG9uZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBQb3AoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgYmxvY2tTaXplLCBlcnIgOj0gcS5wZWVrKHEuaGVhZCkKCWlmIGVyciAhPSBuaWwgewoJCXJldHVybiBuaWwsIGVycgoJfQoKCXEuaGVhZCArPSBibG9ja1NpemUKCXEuY291bnQtLQoKCWlmIHEuaGVhZCA9PSBxLnJpZ2h0TWFyZ2luIHsKCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQlpZiBxLnRhaWwgPT0gcS5yaWdodE1hcmdpbiB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0KCQlxLnJpZ2h0TWFyZ2luID0gcS50YWlsCgl9CgoJcS5mdWxsID0gZmFsc2UKCglyZXR1cm4gZGF0YSwgbmlsCn0KCi8vIFBlZWsgcmVhZHMgdGhlIG9sZGVzdCBlbnRyeSBmcm9tIGxpc3Qgd2l0aG91dCBtb3ZpbmcgaGVhZCBwb2ludGVyCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIFBlZWsoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgXywgZXJyIDo9IHEucGVlayhxLmhlYWQpCglyZXR1cm4gZGF0YSwgZXJyCn0KCi8vIEdldCByZWFkcyBlbnRyeSBmcm9tIGluZGV4CmZ1bmMgKHEgKkJ5dGVzUXVldWUpIEdldChpbmRleCBpbnQpIChbXWJ5dGUsIGVycm9yKSB7CglkYXRhLCBfLCBlcnIgOj0gcS5wZWVrKGluZGV4KQoJcmV0dXJuIGRhdGEsIGVycgp9CgovLyBDaGVja0dldCBjaGVja3MgaWYgYW4gZW50cnkgY2FuIGJlIHJlYWQgZnJvbSBpbmRleApmdW5jIChxICpCeXRlc1F1ZXVlKSBDaGVja0dldChpbmRleCBpbnQpIGVycm9yIHsKCXJldHVybiBxLnBlZWtDaGVja0VycihpbmRleCkKfQoKLy8gQ2FwYWNpdHkgcmV0dXJucyBudW1iZXIgb2YgYWxsb2NhdGVkIGJ5dGVzIGZvciBxdWV1ZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBDYXBhY2l0eSgpIGludCB7CglyZXR1cm4gcS5jYXBhY2l0eQp9CgovLyBMZW4gcmV0dXJucyBudW1iZXIgb2YgZW50cmllcyBrZXB0IGluIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIExlbigpIGludCB7CglyZXR1cm4gcS5jb3VudAp9CgovLyBFcnJvciByZXR1cm5zIGVycm9yIG1lc3NhZ2UKZnVuYyAoZSAqcXVldWVFcnJvcikgRXJyb3IoKSBzdHJpbmcgewoJcmV0dXJuIGUubWVzc2FnZQp9CgovLyBwZWVrQ2hlY2tFcnIgaXMgaWRlbnRpY2FsIHRvIHBlZWssIGJ1dCBkb2VzIG5vdCBhY3R1YWxseSByZXR1cm4gYW55IGRhdGEKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgcGVla0NoZWNrRXJyKGluZGV4IGludCkgZXJyb3IgewoKCWlmIHEuY291bnQgPT0gMCB7CgkJcmV0dXJuIGVyckVtcHR5UXVldWUKCX0KCglpZiBpbmRleCA8PSAwIHsKCQlyZXR1cm4gZXJySW52YWxpZEluZGV4Cgl9CgoJaWYgaW5kZXggPj0gbGVuKHEuYXJyYXkpIHsKCQlyZXR1cm4gZXJySW5kZXhPdXRPZkJvdW5kcwoJfQoJcmV0dXJuIG5pbAp9CgovLyBwZWVrIHJldHVybnMgdGhlIGRhdGEgZnJvbSBpbmRleCBhbmQgdGhlIG51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgdGhlIGxlbmd0aCBvZiB0aGUgZGF0YSBpbiB1dmFyaW50IGZvcm1hdApmdW5jIChxICpCeXRlc1F1ZXVlKSBwZWVrKGluZGV4IGludCkgKFtdYnl0ZSwgaW50LCBlcnJvcikgewoJZXJyIDo9IHEucGVla0NoZWNrRXJyKGluZGV4KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgMCwgZXJyCgl9CgoJYmxvY2tTaXplLCBuIDo9IGJpbmFyeS5VdmFyaW50KHEuYXJyYXlbaW5kZXg6XSkKCXJldHVybiBxLmFycmF5W2luZGV4K24gOiBpbmRleCtpbnQoYmxvY2tTaXplKV0sIGludChibG9ja1NpemUpLCBuaWwKfQoKLy8gY2FuSW5zZXJ0QWZ0ZXJUYWlsIHJldHVybnMgdHJ1ZSBpZiBpdCdzIHBvc3NpYmxlIHRvIGluc2VydCBhbiBlbnRyeSBvZiBzaXplIG9mIG5lZWQgYWZ0ZXIgdGhlIHRhaWwgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEFmdGVyVGFpbChuZWVkIGludCkgYm9vbCB7CglpZiBxLmZ1bGwgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgcS50YWlsID49IHEuaGVhZCB7CgkJcmV0dXJuIHEuY2FwYWNpdHktcS50YWlsID49IG5lZWQKCX0KCS8vIDEuIHRoZXJlIGlzIGV4YWN0bHkgbmVlZCBieXRlcyBiZXR3ZWVuIGhlYWQgYW5kIHRhaWwsIHNvIHdlIGRvIG5vdCBuZWVkCgkvLyB0byByZXNlcnZlIGV4dHJhIHNwYWNlIGZvciBhIHBvdGVudGlhbCBlbXB0eSBlbnRyeSB3aGVuIHJlYWxsb2MgdGhpcyBxdWV1ZQoJLy8gMi4gc3RpbGwgaGF2ZSB1bnVzZWQgc3BhY2UgYmV0d2VlbiB0YWlsIGFuZCBoZWFkLCB0aGVuIHdlIG11c3QgcmVzZXJ2ZQoJLy8gYXQgbGVhc3QgaGVhZGVyRW50cnlTaXplIGJ5dGVzIHNvIHdlIGNhbiBwdXQgYW4gZW1wdHkgZW50cnkKCXJldHVybiBxLmhlYWQtcS50YWlsID09IG5lZWQgfHwgcS5oZWFkLXEudGFpbCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCn0KCi8vIGNhbkluc2VydEJlZm9yZUhlYWQgcmV0dXJucyB0cnVlIGlmIGl0J3MgcG9zc2libGUgdG8gaW5zZXJ0IGFuIGVudHJ5IG9mIHNpemUgb2YgbmVlZCBiZWZvcmUgdGhlIGhlYWQgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEJlZm9yZUhlYWQobmVlZCBpbnQpIGJvb2wgewoJaWYgcS5mdWxsIHsKCQlyZXR1cm4gZmFsc2UKCX0KCWlmIHEudGFpbCA+PSBxLmhlYWQgewoJCXJldHVybiBxLmhlYWQtbGVmdE1hcmdpbkluZGV4ID09IG5lZWQgfHwgcS5oZWFkLWxlZnRNYXJnaW5JbmRleCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCgl9CglyZXR1cm4gcS5oZWFkLXEudGFpbCA9PSBuZWVkIHx8IHEuaGVhZC1xLnRhaWwgPj0gbmVlZCttaW5pbXVtSGVhZGVyU2l6ZQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ab259435c37adf4c5156f0b051641e734b8f3d87 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:ab4340f4d8692396da6a3a98b1c30ffa71fd26da662a1ca2ba20dc4558b4cabd" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..26b98a58f32b687ed8e27653bacdb8ed2029b8a1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/manifest.json @@ -0,0 +1,246 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNilValueCaching" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRetrievingEntryShouldCopy" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotPresent" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithMostShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorInInvalidState" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithAllShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithConcurrentUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestHashCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..2ec7214495bfc3620430723111fe2fa1768d69f7 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__dda0io43/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "d7273f04eabb8b29d00d2d442e6eda551169467c2978475fe05b660ffbed603b", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..bb4a2dc27834388d3d6901ef9b83adf0ed00eee8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize > 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds <= 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i > config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..79693b8f63b9d858622de082dd58322be16bad34 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/instruction.md @@ -0,0 +1,49 @@ +Cache initialization fails with nil pointer dereference + +#### Description + +When creating a new BigCache instance, the cache fails to initialize properly and results in nil pointer dereferences when attempting to use basic operations like Set() and Get(). + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "context" + "time" + + "github.com/allegro/bigcache/v3" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + config.Shards = 1024 + config.HardMaxCacheSize = 8192 + + cache, err := bigcache.New(context.Background(), config) + if err != nil { + panic(err) + } + + // This will cause a nil pointer dereference + cache.Set("key", []byte("value")) + + // This will also cause a nil pointer dereference + value, err := cache.Get("key") + if err != nil { + panic(err) + } + + println(string(value)) +} +``` + +The cache appears to be created successfully (no error returned), but when trying to perform basic operations like Set() or Get(), the program crashes with: + +``` +panic: runtime error: invalid memory address or nil pointer dereference +``` + +This suggests that the cache shards are not being properly initialized during cache creation, even though the constructor doesn't return an error. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..7c6f5448afd2f0ba59fb1f0ad5062bdcabe7e498 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/provenance.json @@ -0,0 +1,372 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "bigcache.go": { + "mode": "0o644", + "sha256": "c4f9cfb68ac4391513a99497470960f20c6a0cd10445cee756a26c95d17c1eb1", + "size": 7884 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 2, + "original_patch_sha256": "03d809051b4a0802d6aa8ded9fcb140d4e82aa17f411facc2607a42ff8d85ea4", + "retained_mutation_file": "bigcache.go", + "retained_mutation_hunk_sha256": "44440ea4b2ea1bcc3aa0923e11e54b22ee060e943d7c072860786304149501d0" + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "f469d53ecbd21dd3caa7e465462cce344b311c6d705ba31951b5f10f67a34536", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "f03788ba2cd35d86e6a5f238e2b7b2ced23a36d8d9cd62d44eee724b80f31626", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "9cef8563d047575ebc42110743e7b817894c8f07e87d892675e469590ebeaf51", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "78ffd78e0f9070fd2fa0ab5b8d0cb93cbfccae4d5daf24795563c853b0e3d5b0", + "is_fork": true, + "learner_path": "tasks/d7e8e1ab5d8107c3224c560f/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/407db55df6f57ec0506309176c0f87d94cd9ed85/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "03d809051b4a0802d6aa8ded9fcb140d4e82aa17f411facc2607a42ff8d85ea4", + "provenance_path": "tasks/d7e8e1ab5d8107c3224c560f/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "407db55df6f57ec0506309176c0f87d94cd9ed85", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "60f1c3715cbd9a5e32f63994f6ce20a029cf2056", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes", + "task_sha256": "64ddf6555a29ed817d4941227a6c79f3145020f51bcfed20d3a090efec72cf07", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "270c8a28a7d168fb9d430af51d66fdeaacd47bfb522b93f3d86ad5663f609075", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e20771b34c4feaadd38f3aa1c59b581fe4d7ea5a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bigcache.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJjb250ZXh0IgoJImVycm9ycyIKCSJ0aW1lIgopCgpjb25zdCAoCgltaW5pbXVtRW50cmllc0luU2hhcmQgPSAxMCAvLyBNaW5pbXVtIG51bWJlciBvZiBlbnRyaWVzIGluIHNpbmdsZSBzaGFyZAopCgovLyBCaWdDYWNoZSBpcyBmYXN0LCBjb25jdXJyZW50LCBldmljdGluZyBjYWNoZSBjcmVhdGVkIHRvIGtlZXAgYmlnIG51bWJlciBvZiBlbnRyaWVzIHdpdGhvdXQgaW1wYWN0IG9uIHBlcmZvcm1hbmNlLgovLyBJdCBrZWVwcyBlbnRyaWVzIG9uIGhlYXAgYnV0IG9taXRzIEdDIGZvciB0aGVtLiBUbyBhY2hpZXZlIHRoYXQsIG9wZXJhdGlvbnMgdGFrZSBwbGFjZSBvbiBieXRlIGFycmF5cywKLy8gdGhlcmVmb3JlIGVudHJpZXMgKGRlKXNlcmlhbGl6YXRpb24gaW4gZnJvbnQgb2YgdGhlIGNhY2hlIHdpbGwgYmUgbmVlZGVkIGluIG1vc3QgdXNlIGNhc2VzLgp0eXBlIEJpZ0NhY2hlIHN0cnVjdCB7CglzaGFyZHMgICAgIFtdKmNhY2hlU2hhcmQKCWxpZmVXaW5kb3cgdWludDY0CgljbG9jayAgICAgIGNsb2NrCgloYXNoICAgICAgIEhhc2hlcgoJY29uZmlnICAgICBDb25maWcKCXNoYXJkTWFzayAgdWludDY0CgljbG9zZSAgICAgIGNoYW4gc3RydWN0e30KfQoKLy8gUmVzcG9uc2Ugd2lsbCBjb250YWluIG1ldGFkYXRhIGFib3V0IHRoZSBlbnRyeSBmb3Igd2hpY2ggR2V0V2l0aEluZm8oa2V5KSB3YXMgY2FsbGVkCnR5cGUgUmVzcG9uc2Ugc3RydWN0IHsKCUVudHJ5U3RhdHVzIFJlbW92ZVJlYXNvbgp9CgovLyBSZW1vdmVSZWFzb24gaXMgYSB2YWx1ZSB1c2VkIHRvIHNpZ25hbCB0byB0aGUgdXNlciB3aHkgYSBwYXJ0aWN1bGFyIGtleSB3YXMgcmVtb3ZlZCBpbiB0aGUgT25SZW1vdmUgY2FsbGJhY2suCnR5cGUgUmVtb3ZlUmVhc29uIHVpbnQzMgoKY29uc3QgKAoJLy8gRXhwaXJlZCBtZWFucyB0aGUga2V5IGlzIHBhc3QgaXRzIExpZmVXaW5kb3cuCglFeHBpcmVkID0gUmVtb3ZlUmVhc29uKDEpCgkvLyBOb1NwYWNlIG1lYW5zIHRoZSBrZXkgaXMgdGhlIG9sZGVzdCBhbmQgdGhlIGNhY2hlIHNpemUgd2FzIGF0IGl0cyBtYXhpbXVtIHdoZW4gU2V0IHdhcyBjYWxsZWQsIG9yIHRoZQoJLy8gZW50cnkgZXhjZWVkZWQgdGhlIG1heGltdW0gc2hhcmQgc2l6ZS4KCU5vU3BhY2UgPSBSZW1vdmVSZWFzb24oMikKCS8vIERlbGV0ZWQgbWVhbnMgRGVsZXRlIHdhcyBjYWxsZWQgYW5kIHRoaXMga2V5IHdhcyByZW1vdmVkIGFzIGEgcmVzdWx0LgoJRGVsZXRlZCA9IFJlbW92ZVJlYXNvbigzKQopCgovLyBOZXcgaW5pdGlhbGl6ZSBuZXcgaW5zdGFuY2Ugb2YgQmlnQ2FjaGUKZnVuYyBOZXcoY3R4IGNvbnRleHQuQ29udGV4dCwgY29uZmlnIENvbmZpZykgKCpCaWdDYWNoZSwgZXJyb3IpIHsKCXJldHVybiBuZXdCaWdDYWNoZShjdHgsIGNvbmZpZywgJnN5c3RlbUNsb2Nre30pCn0KCi8vIE5ld0JpZ0NhY2hlIGluaXRpYWxpemUgbmV3IGluc3RhbmNlIG9mIEJpZ0NhY2hlCi8vCi8vIERlcHJlY2F0ZWQ6IE5ld0JpZ0NhY2hlIGlzIGRlcHJlY2F0ZWQsIHBsZWFzZSB1c2UgTmV3KGN0eCwgY29uZmlnKSBpbnN0ZWFkLAovLyBOZXcgdGFrZXMgaW4gY29udGV4dCBhbmQgY2FuIGdyYWNlZnVsbHkKLy8gc2h1dGRvd24gd2l0aCBjb250ZXh0IGNhbmNlbGxhdGlvbnMKZnVuYyBOZXdCaWdDYWNoZShjb25maWcgQ29uZmlnKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJcmV0dXJuIG5ld0JpZ0NhY2hlKGNvbnRleHQuQmFja2dyb3VuZCgpLCBjb25maWcsICZzeXN0ZW1DbG9ja3t9KQp9CgpmdW5jIG5ld0JpZ0NhY2hlKGN0eCBjb250ZXh0LkNvbnRleHQsIGNvbmZpZyBDb25maWcsIGNsb2NrIGNsb2NrKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJaWYgIWlzUG93ZXJPZlR3byhjb25maWcuU2hhcmRzKSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiU2hhcmRzIG51bWJlciBtdXN0IGJlIHBvd2VyIG9mIHR3byIpCgl9CglpZiBjb25maWcuTWF4RW50cnlTaXplIDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cnlTaXplIG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuTWF4RW50cmllc0luV2luZG93IDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cmllc0luV2luZG93IG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuSGFyZE1heENhY2hlU2l6ZSA8IDAgewoJCXJldHVybiBuaWwsIGVycm9ycy5OZXcoIkhhcmRNYXhDYWNoZVNpemUgbXVzdCBiZSA+PSAwIikKCX0KCglsaWZlV2luZG93U2Vjb25kcyA6PSB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKQoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCAmJiBsaWZlV2luZG93U2Vjb25kcyA9PSAwIHsKCQlyZXR1cm4gbmlsLCBlcnJvcnMuTmV3KCJMaWZlV2luZG93IG11c3QgYmUgPj0gMXMgd2hlbiBDbGVhbldpbmRvdyBpcyBzZXQiKQoJfQoKCWlmIGNvbmZpZy5IYXNoZXIgPT0gbmlsIHsKCQljb25maWcuSGFzaGVyID0gbmV3RGVmYXVsdEhhc2hlcigpCgl9CgoJY2FjaGUgOj0gJkJpZ0NhY2hlewoJCXNoYXJkczogICAgIG1ha2UoW10qY2FjaGVTaGFyZCwgY29uZmlnLlNoYXJkcyksCgkJbGlmZVdpbmRvdzogbGlmZVdpbmRvd1NlY29uZHMsCgkJY2xvY2s6ICAgICAgY2xvY2ssCgkJaGFzaDogICAgICAgY29uZmlnLkhhc2hlciwKCQljb25maWc6ICAgICBjb25maWcsCgkJc2hhcmRNYXNrOiAgdWludDY0KGNvbmZpZy5TaGFyZHMgLSAxKSwKCQljbG9zZTogICAgICBtYWtlKGNoYW4gc3RydWN0e30pLAoJfQoKCXZhciBvblJlbW92ZSBmdW5jKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pCglpZiBjb25maWcuT25SZW1vdmVXaXRoTWV0YWRhdGEgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmVXaXRoTWV0YWRhdGEKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmUgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmUKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmVXaXRoUmVhc29uICE9IG5pbCB7CgkJb25SZW1vdmUgPSBjYWNoZS5wcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbgoJfSBlbHNlIHsKCQlvblJlbW92ZSA9IGNhY2hlLm5vdFByb3ZpZGVkT25SZW1vdmUKCX0KCglmb3IgaSA6PSAwOyBpIDwgY29uZmlnLlNoYXJkczsgaSsrIHsKCQljYWNoZS5zaGFyZHNbaV0gPSBpbml0TmV3U2hhcmQoY29uZmlnLCBvblJlbW92ZSwgY2xvY2spCgl9CgoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCB7CgkJZ28gZnVuYygpIHsKCQkJdGlja2VyIDo9IHRpbWUuTmV3VGlja2VyKGNvbmZpZy5DbGVhbldpbmRvdykKCQkJZGVmZXIgdGlja2VyLlN0b3AoKQoJCQlmb3IgewoJCQkJc2VsZWN0IHsKCQkJCWNhc2UgPC1jdHguRG9uZSgpOgoJCQkJCXJldHVybgoJCQkJY2FzZSB0IDo9IDwtdGlja2VyLkM6CgkJCQkJY2FjaGUuY2xlYW5VcCh1aW50NjQodC5Vbml4KCkpKQoJCQkJY2FzZSA8LWNhY2hlLmNsb3NlOgoJCQkJCXJldHVybgoJCQkJfQoJCQl9CgkJfSgpCgl9CgoJcmV0dXJuIGNhY2hlLCBuaWwKfQoKLy8gQ2xvc2UgaXMgdXNlZCB0byBzaWduYWwgYSBzaHV0ZG93biBvZiB0aGUgY2FjaGUgd2hlbiB5b3UgYXJlIGRvbmUgd2l0aCBpdC4KLy8gVGhpcyBhbGxvd3MgdGhlIGNsZWFuaW5nIGdvcm91dGluZXMgdG8gZXhpdCBhbmQgZW5zdXJlcyByZWZlcmVuY2VzIGFyZSBub3QKLy8ga2VwdCB0byB0aGUgY2FjaGUgcHJldmVudGluZyBHQyBvZiB0aGUgZW50aXJlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2xvc2UoKSBlcnJvciB7CgljbG9zZShjLmNsb3NlKQoJcmV0dXJuIG5pbAp9CgovLyBHZXQgcmVhZHMgZW50cnkgZm9yIHRoZSBrZXkuCi8vIEl0IHJldHVybnMgYW4gRXJyRW50cnlOb3RGb3VuZCB3aGVuCi8vIG5vIGVudHJ5IGV4aXN0cyBmb3IgdGhlIGdpdmVuIGtleS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEdldChrZXkgc3RyaW5nKSAoW11ieXRlLCBlcnJvcikgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5nZXQoa2V5LCBoYXNoZWRLZXkpCn0KCi8vIEdldFdpdGhJbmZvIHJlYWRzIGVudHJ5IGZvciB0aGUga2V5IHdpdGggUmVzcG9uc2UgaW5mby4KLy8gSXQgcmV0dXJucyBhbiBFcnJFbnRyeU5vdEZvdW5kIHdoZW4KLy8gbm8gZW50cnkgZXhpc3RzIGZvciB0aGUgZ2l2ZW4ga2V5LgpmdW5jIChjICpCaWdDYWNoZSkgR2V0V2l0aEluZm8oa2V5IHN0cmluZykgKFtdYnl0ZSwgUmVzcG9uc2UsIGVycm9yKSB7CgloYXNoZWRLZXkgOj0gYy5oYXNoLlN1bTY0KGtleSkKCXNoYXJkIDo9IGMuZ2V0U2hhcmQoaGFzaGVkS2V5KQoJcmV0dXJuIHNoYXJkLmdldFdpdGhJbmZvKGtleSwgaGFzaGVkS2V5KQp9CgovLyBTZXQgc2F2ZXMgZW50cnkgdW5kZXIgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgU2V0KGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5zZXQoa2V5LCBoYXNoZWRLZXksIGVudHJ5KQp9CgovLyBBcHBlbmQgYXBwZW5kcyBlbnRyeSB1bmRlciB0aGUga2V5IGlmIGtleSBleGlzdHMsIG90aGVyd2lzZQovLyBpdCB3aWxsIHNldCB0aGUga2V5IChzYW1lIGJlaGF2aW91ciBhcyBTZXQoKSkuIFdpdGggQXBwZW5kKCkgeW91IGNhbgovLyBjb25jYXRlbmF0ZSBtdWx0aXBsZSBlbnRyaWVzIHVuZGVyIHRoZSBzYW1lIGtleSBpbiBhIGxvY2stb3B0aW1pemVkIHdheS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEFwcGVuZChrZXkgc3RyaW5nLCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuYXBwZW5kKGtleSwgaGFzaGVkS2V5LCBlbnRyeSkKfQoKLy8gRGVsZXRlIHJlbW92ZXMgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgRGVsZXRlKGtleSBzdHJpbmcpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZGVsKGhhc2hlZEtleSkKfQoKLy8gUmVzZXQgZW1wdGllcyBhbGwgY2FjaGUgc2hhcmRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldCgpIGVycm9yIHsKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJc2hhcmQucmVzZXQoYy5jb25maWcpCgl9CglyZXR1cm4gbmlsCn0KCi8vIFJlc2V0U3RhdHMgcmVzZXRzIGNhY2hlIHN0YXRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldFN0YXRzKCkgZXJyb3IgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5yZXNldFN0YXRzKCkKCX0KCXJldHVybiBuaWwKfQoKLy8gTGVuIGNvbXB1dGVzIHRoZSBudW1iZXIgb2YgZW50cmllcyBpbiB0aGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBMZW4oKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmxlbigpCgl9CglyZXR1cm4gbGVuCn0KCi8vIENhcGFjaXR5IHJldHVybnMgdGhlIGFtb3VudCBvZiBieXRlcyBzdG9yZWQgaW4gdGhlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2FwYWNpdHkoKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmNhcGFjaXR5KCkKCX0KCXJldHVybiBsZW4KfQoKLy8gU3RhdHMgcmV0dXJucyBjYWNoZSdzIHN0YXRpc3RpY3MKZnVuYyAoYyAqQmlnQ2FjaGUpIFN0YXRzKCkgU3RhdHMgewoJdmFyIHMgU3RhdHMKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJdG1wIDo9IHNoYXJkLmdldFN0YXRzKCkKCQlzLkhpdHMgKz0gdG1wLkhpdHMKCQlzLk1pc3NlcyArPSB0bXAuTWlzc2VzCgkJcy5EZWxIaXRzICs9IHRtcC5EZWxIaXRzCgkJcy5EZWxNaXNzZXMgKz0gdG1wLkRlbE1pc3NlcwoJCXMuQ29sbGlzaW9ucyArPSB0bXAuQ29sbGlzaW9ucwoJfQoJcmV0dXJuIHMKfQoKLy8gS2V5TWV0YWRhdGEgcmV0dXJucyBudW1iZXIgb2YgdGltZXMgYSBjYWNoZWQgcmVzb3VyY2Ugd2FzIHJlcXVlc3RlZC4KZnVuYyAoYyAqQmlnQ2FjaGUpIEtleU1ldGFkYXRhKGtleSBzdHJpbmcpIE1ldGFkYXRhIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZ2V0S2V5TWV0YWRhdGFXaXRoTG9jayhoYXNoZWRLZXkpCn0KCi8vIEl0ZXJhdG9yIHJldHVybnMgaXRlcmF0b3IgZnVuY3Rpb24gdG8gaXRlcmF0ZSBvdmVyIEVudHJ5SW5mbydzIGZyb20gd2hvbGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBJdGVyYXRvcigpICpFbnRyeUluZm9JdGVyYXRvciB7CglyZXR1cm4gbmV3SXRlcmF0b3IoYykKfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPCBvbGRlc3RUaW1lc3RhbXAgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgY3VycmVudFRpbWVzdGFtcC1vbGRlc3RUaW1lc3RhbXAgPiBjLmxpZmVXaW5kb3cgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChjICpCaWdDYWNoZSkgY2xlYW5VcChjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5jbGVhblVwKGN1cnJlbnRUaW1lc3RhbXApCgl9Cn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBnZXRTaGFyZChoYXNoZWRLZXkgdWludDY0KSAoc2hhcmQgKmNhY2hlU2hhcmQpIHsKCXJldHVybiBjLnNoYXJkc1toYXNoZWRLZXkmYy5zaGFyZE1hc2tdCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pIHsKCWMuY29uZmlnLk9uUmVtb3ZlKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkpCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbih3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglpZiBjLmNvbmZpZy5vblJlbW92ZUZpbHRlciA9PSAwIHx8ICgxPDx1aW50KHJlYXNvbikpJmMuY29uZmlnLm9uUmVtb3ZlRmlsdGVyID4gMCB7CgkJYy5jb25maWcuT25SZW1vdmVXaXRoUmVhc29uKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHJlYXNvbikKCX0KfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG5vdFByb3ZpZGVkT25SZW1vdmUod3JhcHBlZEVudHJ5IFtdYnl0ZSwgcmVhc29uIFJlbW92ZVJlYXNvbikgewp9CgpmdW5jIChjICpCaWdDYWNoZSkgcHJvdmlkZWRPblJlbW92ZVdpdGhNZXRhZGF0YSh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglrZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCWMuY29uZmlnLk9uUmVtb3ZlV2l0aE1ldGFkYXRhKGtleSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHNoYXJkLmdldEtleU1ldGFkYXRhKGhhc2hlZEtleSkpCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..28381f3f8e2a3b3e7489dab55ab69f015ff6916c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:7914b9bc2d9b8c9da57b24ca1e0a3a3632a0ce2dde140412ec93ad856105ab9e" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..c23059c04deba40f2a8e177d47afda0448160650 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/manifest.json @@ -0,0 +1,186 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/partial-repair.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..191d48a0066cc44a67e43dc9f54531e8e0f8cbf6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bigcache.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJjb250ZXh0IgoJImVycm9ycyIKCSJ0aW1lIgopCgpjb25zdCAoCgltaW5pbXVtRW50cmllc0luU2hhcmQgPSAxMCAvLyBNaW5pbXVtIG51bWJlciBvZiBlbnRyaWVzIGluIHNpbmdsZSBzaGFyZAopCgovLyBCaWdDYWNoZSBpcyBmYXN0LCBjb25jdXJyZW50LCBldmljdGluZyBjYWNoZSBjcmVhdGVkIHRvIGtlZXAgYmlnIG51bWJlciBvZiBlbnRyaWVzIHdpdGhvdXQgaW1wYWN0IG9uIHBlcmZvcm1hbmNlLgovLyBJdCBrZWVwcyBlbnRyaWVzIG9uIGhlYXAgYnV0IG9taXRzIEdDIGZvciB0aGVtLiBUbyBhY2hpZXZlIHRoYXQsIG9wZXJhdGlvbnMgdGFrZSBwbGFjZSBvbiBieXRlIGFycmF5cywKLy8gdGhlcmVmb3JlIGVudHJpZXMgKGRlKXNlcmlhbGl6YXRpb24gaW4gZnJvbnQgb2YgdGhlIGNhY2hlIHdpbGwgYmUgbmVlZGVkIGluIG1vc3QgdXNlIGNhc2VzLgp0eXBlIEJpZ0NhY2hlIHN0cnVjdCB7CglzaGFyZHMgICAgIFtdKmNhY2hlU2hhcmQKCWxpZmVXaW5kb3cgdWludDY0CgljbG9jayAgICAgIGNsb2NrCgloYXNoICAgICAgIEhhc2hlcgoJY29uZmlnICAgICBDb25maWcKCXNoYXJkTWFzayAgdWludDY0CgljbG9zZSAgICAgIGNoYW4gc3RydWN0e30KfQoKLy8gUmVzcG9uc2Ugd2lsbCBjb250YWluIG1ldGFkYXRhIGFib3V0IHRoZSBlbnRyeSBmb3Igd2hpY2ggR2V0V2l0aEluZm8oa2V5KSB3YXMgY2FsbGVkCnR5cGUgUmVzcG9uc2Ugc3RydWN0IHsKCUVudHJ5U3RhdHVzIFJlbW92ZVJlYXNvbgp9CgovLyBSZW1vdmVSZWFzb24gaXMgYSB2YWx1ZSB1c2VkIHRvIHNpZ25hbCB0byB0aGUgdXNlciB3aHkgYSBwYXJ0aWN1bGFyIGtleSB3YXMgcmVtb3ZlZCBpbiB0aGUgT25SZW1vdmUgY2FsbGJhY2suCnR5cGUgUmVtb3ZlUmVhc29uIHVpbnQzMgoKY29uc3QgKAoJLy8gRXhwaXJlZCBtZWFucyB0aGUga2V5IGlzIHBhc3QgaXRzIExpZmVXaW5kb3cuCglFeHBpcmVkID0gUmVtb3ZlUmVhc29uKDEpCgkvLyBOb1NwYWNlIG1lYW5zIHRoZSBrZXkgaXMgdGhlIG9sZGVzdCBhbmQgdGhlIGNhY2hlIHNpemUgd2FzIGF0IGl0cyBtYXhpbXVtIHdoZW4gU2V0IHdhcyBjYWxsZWQsIG9yIHRoZQoJLy8gZW50cnkgZXhjZWVkZWQgdGhlIG1heGltdW0gc2hhcmQgc2l6ZS4KCU5vU3BhY2UgPSBSZW1vdmVSZWFzb24oMikKCS8vIERlbGV0ZWQgbWVhbnMgRGVsZXRlIHdhcyBjYWxsZWQgYW5kIHRoaXMga2V5IHdhcyByZW1vdmVkIGFzIGEgcmVzdWx0LgoJRGVsZXRlZCA9IFJlbW92ZVJlYXNvbigzKQopCgovLyBOZXcgaW5pdGlhbGl6ZSBuZXcgaW5zdGFuY2Ugb2YgQmlnQ2FjaGUKZnVuYyBOZXcoY3R4IGNvbnRleHQuQ29udGV4dCwgY29uZmlnIENvbmZpZykgKCpCaWdDYWNoZSwgZXJyb3IpIHsKCXJldHVybiBuZXdCaWdDYWNoZShjdHgsIGNvbmZpZywgJnN5c3RlbUNsb2Nre30pCn0KCi8vIE5ld0JpZ0NhY2hlIGluaXRpYWxpemUgbmV3IGluc3RhbmNlIG9mIEJpZ0NhY2hlCi8vCi8vIERlcHJlY2F0ZWQ6IE5ld0JpZ0NhY2hlIGlzIGRlcHJlY2F0ZWQsIHBsZWFzZSB1c2UgTmV3KGN0eCwgY29uZmlnKSBpbnN0ZWFkLAovLyBOZXcgdGFrZXMgaW4gY29udGV4dCBhbmQgY2FuIGdyYWNlZnVsbHkKLy8gc2h1dGRvd24gd2l0aCBjb250ZXh0IGNhbmNlbGxhdGlvbnMKZnVuYyBOZXdCaWdDYWNoZShjb25maWcgQ29uZmlnKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJcmV0dXJuIG5ld0JpZ0NhY2hlKGNvbnRleHQuQmFja2dyb3VuZCgpLCBjb25maWcsICZzeXN0ZW1DbG9ja3t9KQp9CgpmdW5jIG5ld0JpZ0NhY2hlKGN0eCBjb250ZXh0LkNvbnRleHQsIGNvbmZpZyBDb25maWcsIGNsb2NrIGNsb2NrKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJaWYgIWlzUG93ZXJPZlR3byhjb25maWcuU2hhcmRzKSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiU2hhcmRzIG51bWJlciBtdXN0IGJlIHBvd2VyIG9mIHR3byIpCgl9CglpZiBjb25maWcuTWF4RW50cnlTaXplIDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cnlTaXplIG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuTWF4RW50cmllc0luV2luZG93IDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cmllc0luV2luZG93IG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuSGFyZE1heENhY2hlU2l6ZSA+IDAgewoJCXJldHVybiBuaWwsIGVycm9ycy5OZXcoIkhhcmRNYXhDYWNoZVNpemUgbXVzdCBiZSA+PSAwIikKCX0KCglsaWZlV2luZG93U2Vjb25kcyA6PSB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKQoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCAmJiBsaWZlV2luZG93U2Vjb25kcyA8PSAwIHsKCQlyZXR1cm4gbmlsLCBlcnJvcnMuTmV3KCJMaWZlV2luZG93IG11c3QgYmUgPj0gMXMgd2hlbiBDbGVhbldpbmRvdyBpcyBzZXQiKQoJfQoKCWlmIGNvbmZpZy5IYXNoZXIgPT0gbmlsIHsKCQljb25maWcuSGFzaGVyID0gbmV3RGVmYXVsdEhhc2hlcigpCgl9CgoJY2FjaGUgOj0gJkJpZ0NhY2hlewoJCXNoYXJkczogICAgIG1ha2UoW10qY2FjaGVTaGFyZCwgY29uZmlnLlNoYXJkcyksCgkJbGlmZVdpbmRvdzogbGlmZVdpbmRvd1NlY29uZHMsCgkJY2xvY2s6ICAgICAgY2xvY2ssCgkJaGFzaDogICAgICAgY29uZmlnLkhhc2hlciwKCQljb25maWc6ICAgICBjb25maWcsCgkJc2hhcmRNYXNrOiAgdWludDY0KGNvbmZpZy5TaGFyZHMgLSAxKSwKCQljbG9zZTogICAgICBtYWtlKGNoYW4gc3RydWN0e30pLAoJfQoKCXZhciBvblJlbW92ZSBmdW5jKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pCglpZiBjb25maWcuT25SZW1vdmVXaXRoTWV0YWRhdGEgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmVXaXRoTWV0YWRhdGEKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmUgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmUKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmVXaXRoUmVhc29uICE9IG5pbCB7CgkJb25SZW1vdmUgPSBjYWNoZS5wcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbgoJfSBlbHNlIHsKCQlvblJlbW92ZSA9IGNhY2hlLm5vdFByb3ZpZGVkT25SZW1vdmUKCX0KCglmb3IgaSA6PSAwOyBpIDwgY29uZmlnLlNoYXJkczsgaSsrIHsKCQljYWNoZS5zaGFyZHNbaV0gPSBpbml0TmV3U2hhcmQoY29uZmlnLCBvblJlbW92ZSwgY2xvY2spCgl9CgoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCB7CgkJZ28gZnVuYygpIHsKCQkJdGlja2VyIDo9IHRpbWUuTmV3VGlja2VyKGNvbmZpZy5DbGVhbldpbmRvdykKCQkJZGVmZXIgdGlja2VyLlN0b3AoKQoJCQlmb3IgewoJCQkJc2VsZWN0IHsKCQkJCWNhc2UgPC1jdHguRG9uZSgpOgoJCQkJCXJldHVybgoJCQkJY2FzZSB0IDo9IDwtdGlja2VyLkM6CgkJCQkJY2FjaGUuY2xlYW5VcCh1aW50NjQodC5Vbml4KCkpKQoJCQkJY2FzZSA8LWNhY2hlLmNsb3NlOgoJCQkJCXJldHVybgoJCQkJfQoJCQl9CgkJfSgpCgl9CgoJcmV0dXJuIGNhY2hlLCBuaWwKfQoKLy8gQ2xvc2UgaXMgdXNlZCB0byBzaWduYWwgYSBzaHV0ZG93biBvZiB0aGUgY2FjaGUgd2hlbiB5b3UgYXJlIGRvbmUgd2l0aCBpdC4KLy8gVGhpcyBhbGxvd3MgdGhlIGNsZWFuaW5nIGdvcm91dGluZXMgdG8gZXhpdCBhbmQgZW5zdXJlcyByZWZlcmVuY2VzIGFyZSBub3QKLy8ga2VwdCB0byB0aGUgY2FjaGUgcHJldmVudGluZyBHQyBvZiB0aGUgZW50aXJlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2xvc2UoKSBlcnJvciB7CgljbG9zZShjLmNsb3NlKQoJcmV0dXJuIG5pbAp9CgovLyBHZXQgcmVhZHMgZW50cnkgZm9yIHRoZSBrZXkuCi8vIEl0IHJldHVybnMgYW4gRXJyRW50cnlOb3RGb3VuZCB3aGVuCi8vIG5vIGVudHJ5IGV4aXN0cyBmb3IgdGhlIGdpdmVuIGtleS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEdldChrZXkgc3RyaW5nKSAoW11ieXRlLCBlcnJvcikgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5nZXQoa2V5LCBoYXNoZWRLZXkpCn0KCi8vIEdldFdpdGhJbmZvIHJlYWRzIGVudHJ5IGZvciB0aGUga2V5IHdpdGggUmVzcG9uc2UgaW5mby4KLy8gSXQgcmV0dXJucyBhbiBFcnJFbnRyeU5vdEZvdW5kIHdoZW4KLy8gbm8gZW50cnkgZXhpc3RzIGZvciB0aGUgZ2l2ZW4ga2V5LgpmdW5jIChjICpCaWdDYWNoZSkgR2V0V2l0aEluZm8oa2V5IHN0cmluZykgKFtdYnl0ZSwgUmVzcG9uc2UsIGVycm9yKSB7CgloYXNoZWRLZXkgOj0gYy5oYXNoLlN1bTY0KGtleSkKCXNoYXJkIDo9IGMuZ2V0U2hhcmQoaGFzaGVkS2V5KQoJcmV0dXJuIHNoYXJkLmdldFdpdGhJbmZvKGtleSwgaGFzaGVkS2V5KQp9CgovLyBTZXQgc2F2ZXMgZW50cnkgdW5kZXIgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgU2V0KGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5zZXQoa2V5LCBoYXNoZWRLZXksIGVudHJ5KQp9CgovLyBBcHBlbmQgYXBwZW5kcyBlbnRyeSB1bmRlciB0aGUga2V5IGlmIGtleSBleGlzdHMsIG90aGVyd2lzZQovLyBpdCB3aWxsIHNldCB0aGUga2V5IChzYW1lIGJlaGF2aW91ciBhcyBTZXQoKSkuIFdpdGggQXBwZW5kKCkgeW91IGNhbgovLyBjb25jYXRlbmF0ZSBtdWx0aXBsZSBlbnRyaWVzIHVuZGVyIHRoZSBzYW1lIGtleSBpbiBhIGxvY2stb3B0aW1pemVkIHdheS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEFwcGVuZChrZXkgc3RyaW5nLCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuYXBwZW5kKGtleSwgaGFzaGVkS2V5LCBlbnRyeSkKfQoKLy8gRGVsZXRlIHJlbW92ZXMgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgRGVsZXRlKGtleSBzdHJpbmcpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZGVsKGhhc2hlZEtleSkKfQoKLy8gUmVzZXQgZW1wdGllcyBhbGwgY2FjaGUgc2hhcmRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldCgpIGVycm9yIHsKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJc2hhcmQucmVzZXQoYy5jb25maWcpCgl9CglyZXR1cm4gbmlsCn0KCi8vIFJlc2V0U3RhdHMgcmVzZXRzIGNhY2hlIHN0YXRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldFN0YXRzKCkgZXJyb3IgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5yZXNldFN0YXRzKCkKCX0KCXJldHVybiBuaWwKfQoKLy8gTGVuIGNvbXB1dGVzIHRoZSBudW1iZXIgb2YgZW50cmllcyBpbiB0aGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBMZW4oKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmxlbigpCgl9CglyZXR1cm4gbGVuCn0KCi8vIENhcGFjaXR5IHJldHVybnMgdGhlIGFtb3VudCBvZiBieXRlcyBzdG9yZWQgaW4gdGhlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2FwYWNpdHkoKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmNhcGFjaXR5KCkKCX0KCXJldHVybiBsZW4KfQoKLy8gU3RhdHMgcmV0dXJucyBjYWNoZSdzIHN0YXRpc3RpY3MKZnVuYyAoYyAqQmlnQ2FjaGUpIFN0YXRzKCkgU3RhdHMgewoJdmFyIHMgU3RhdHMKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJdG1wIDo9IHNoYXJkLmdldFN0YXRzKCkKCQlzLkhpdHMgKz0gdG1wLkhpdHMKCQlzLk1pc3NlcyArPSB0bXAuTWlzc2VzCgkJcy5EZWxIaXRzICs9IHRtcC5EZWxIaXRzCgkJcy5EZWxNaXNzZXMgKz0gdG1wLkRlbE1pc3NlcwoJCXMuQ29sbGlzaW9ucyArPSB0bXAuQ29sbGlzaW9ucwoJfQoJcmV0dXJuIHMKfQoKLy8gS2V5TWV0YWRhdGEgcmV0dXJucyBudW1iZXIgb2YgdGltZXMgYSBjYWNoZWQgcmVzb3VyY2Ugd2FzIHJlcXVlc3RlZC4KZnVuYyAoYyAqQmlnQ2FjaGUpIEtleU1ldGFkYXRhKGtleSBzdHJpbmcpIE1ldGFkYXRhIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZ2V0S2V5TWV0YWRhdGFXaXRoTG9jayhoYXNoZWRLZXkpCn0KCi8vIEl0ZXJhdG9yIHJldHVybnMgaXRlcmF0b3IgZnVuY3Rpb24gdG8gaXRlcmF0ZSBvdmVyIEVudHJ5SW5mbydzIGZyb20gd2hvbGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBJdGVyYXRvcigpICpFbnRyeUluZm9JdGVyYXRvciB7CglyZXR1cm4gbmV3SXRlcmF0b3IoYykKfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPCBvbGRlc3RUaW1lc3RhbXAgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgY3VycmVudFRpbWVzdGFtcC1vbGRlc3RUaW1lc3RhbXAgPiBjLmxpZmVXaW5kb3cgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChjICpCaWdDYWNoZSkgY2xlYW5VcChjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5jbGVhblVwKGN1cnJlbnRUaW1lc3RhbXApCgl9Cn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBnZXRTaGFyZChoYXNoZWRLZXkgdWludDY0KSAoc2hhcmQgKmNhY2hlU2hhcmQpIHsKCXJldHVybiBjLnNoYXJkc1toYXNoZWRLZXkmYy5zaGFyZE1hc2tdCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pIHsKCWMuY29uZmlnLk9uUmVtb3ZlKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkpCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbih3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglpZiBjLmNvbmZpZy5vblJlbW92ZUZpbHRlciA9PSAwIHx8ICgxPDx1aW50KHJlYXNvbikpJmMuY29uZmlnLm9uUmVtb3ZlRmlsdGVyID4gMCB7CgkJYy5jb25maWcuT25SZW1vdmVXaXRoUmVhc29uKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHJlYXNvbikKCX0KfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG5vdFByb3ZpZGVkT25SZW1vdmUod3JhcHBlZEVudHJ5IFtdYnl0ZSwgcmVhc29uIFJlbW92ZVJlYXNvbikgewp9CgpmdW5jIChjICpCaWdDYWNoZSkgcHJvdmlkZWRPblJlbW92ZVdpdGhNZXRhZGF0YSh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglrZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCWMuY29uZmlnLk9uUmVtb3ZlV2l0aE1ldGFkYXRhKGtleSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHNoYXJkLmdldEtleU1ldGFkYXRhKGhhc2hlZEtleSkpCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..3b2c31204137e6f3664f0a3d3cb20d38fae54ce1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change__umv0enes/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "59635053fcdf0bd2bd3723f269568ff5100c3644ce156a564ce95557553ad3e0", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..562b42a1d23e1f35c6cf1fb8cce3f4639e7eaf9f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 1 { + return errEmptyQueue + } + + if index <= -1 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..613ac2c6ddadcac8a2574cdea0ccca5112291447 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/instruction.md @@ -0,0 +1,41 @@ +BytesQueue peek operations fail with slice bounds out of range when queue has single element + +#### Description + +When a BytesQueue contains exactly one element, peek operations result in a panic with "slice bounds out of range" error. This affects various operations that rely on peeking at queue elements. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/allegro/bigcache/v3/queue" +) + +func main() { + q := queue.NewBytesQueue(1024, 0, false) + + // Push a single element + index, _ := q.Push([]byte("test")) + fmt.Printf("Pushed element at index: %d\n", index) + fmt.Printf("Queue count: %d\n", q.Len()) + + // Try to peek - this should work but panics + data, err := q.Peek(index) + if err != nil { + fmt.Printf("Error: %v\n", err) + } else { + fmt.Printf("Peeked data: %s\n", string(data)) + } +} +``` + +The above code panics with: +``` +panic: runtime error: slice bounds out of range [2:1] +``` + +This also affects BigCache operations when the underlying queue has a single element, causing cache set operations to fail unexpectedly. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..0cfd782a7e412f04779612568a72f702607ebce0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "bb5ebb34d60a520bf1d81693fe655c29ae63102cd059e7e7b55270e7a21f57e2", + "size": 6857 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "5a7d086bb8b3980daec02d590c8817e8f4fbe3843cd555fd674195d43c158055", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "82a06b8f5b0a019dae6f01ccf1f07652fba7c527e403cd3b178836bd32824266", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "205ff5e27208825bb358d08b2c200f260a1556fad59491758a8598d913a13a6d", + "is_fork": true, + "learner_path": "tasks/d4fa27997571b9a508fb9d33/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/e7619abe6a5097e9e4c1790309a3dd22de4b971a/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "52aac1d7381670b965f0e9c5a70d36b06329c998363965effe1d4e6650ee3323", + "provenance_path": "tasks/d4fa27997571b9a508fb9d33/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "e7619abe6a5097e9e4c1790309a3dd22de4b971a", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "248d27fe2f94147b8d9125c9518a803112529f0e", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2", + "task_sha256": "9aca5b08d39040946066bfaedcca73c3b15021126fe3a862741b2e0ff8355958", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "154d8d04df23f341a581b963f6e7bd95210ededf584a099de4dcc3870f856621", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e4f032645f70e7b7e425953ed99476d657d7ce3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"queue/bytes_queue.go": {"data": "cGFja2FnZSBxdWV1ZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCgkibG9nIgoJInRpbWUiCikKCmNvbnN0ICgKCS8vIE51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgMCBpbiB1dmFyaW50IGZvcm1hdAoJbWluaW11bUhlYWRlclNpemUgPSAxNyAvLyAxIGJ5dGUgYmxvYnNpemUgKyB0aW1lc3RhbXBTaXplSW5CeXRlcyArIGhhc2hTaXplSW5CeXRlcwoJLy8gQnl0ZXMgYmVmb3JlIGxlZnQgbWFyZ2luIGFyZSBub3QgdXNlZC4gWmVybyBpbmRleCBtZWFucyBlbGVtZW50IGRvZXMgbm90IGV4aXN0IGluIHF1ZXVlLCB1c2VmdWwgd2hpbGUgcmVhZGluZyBzbGljZSBmcm9tIGluZGV4CglsZWZ0TWFyZ2luSW5kZXggPSAxCikKCnZhciAoCgllcnJFbXB0eVF1ZXVlICAgICAgID0gJnF1ZXVlRXJyb3J7IkVtcHR5IHF1ZXVlIn0KCWVyckludmFsaWRJbmRleCAgICAgPSAmcXVldWVFcnJvcnsiSW5kZXggbXVzdCBiZSBncmVhdGVyIHRoYW4gemVyby4gSW52YWxpZCBpbmRleC4ifQoJZXJySW5kZXhPdXRPZkJvdW5kcyA9ICZxdWV1ZUVycm9yeyJJbmRleCBvdXQgb2YgcmFuZ2UifQopCgovLyBCeXRlc1F1ZXVlIGlzIGEgbm9uLXRocmVhZCBzYWZlIHF1ZXVlIHR5cGUgb2YgZmlmbyBiYXNlZCBvbiBieXRlcyBhcnJheS4KLy8gRm9yIGV2ZXJ5IHB1c2ggb3BlcmF0aW9uIGluZGV4IG9mIGVudHJ5IGlzIHJldHVybmVkLiBJdCBjYW4gYmUgdXNlZCB0byByZWFkIHRoZSBlbnRyeSBsYXRlcgp0eXBlIEJ5dGVzUXVldWUgc3RydWN0IHsKCWZ1bGwgICAgICAgICBib29sCglhcnJheSAgICAgICAgW11ieXRlCgljYXBhY2l0eSAgICAgaW50CgltYXhDYXBhY2l0eSAgaW50CgloZWFkICAgICAgICAgaW50Cgl0YWlsICAgICAgICAgaW50Cgljb3VudCAgICAgICAgaW50CglyaWdodE1hcmdpbiAgaW50CgloZWFkZXJCdWZmZXIgW11ieXRlCgl2ZXJib3NlICAgICAgYm9vbAp9Cgp0eXBlIHF1ZXVlRXJyb3Igc3RydWN0IHsKCW1lc3NhZ2Ugc3RyaW5nCn0KCi8vIGdldE5lZWRlZFNpemUgcmV0dXJucyB0aGUgbnVtYmVyIG9mIGJ5dGVzIGFuIGVudHJ5IG9mIGxlbmd0aCBuZWVkIGluIHRoZSBxdWV1ZQpmdW5jIGdldE5lZWRlZFNpemUobGVuZ3RoIGludCkgaW50IHsKCXZhciBoZWFkZXIgaW50Cglzd2l0Y2ggewoJY2FzZSBsZW5ndGggPCAxMjc6IC8vIDE8PDctMQoJCWhlYWRlciA9IDEKCWNhc2UgbGVuZ3RoIDwgMTYzODI6IC8vIDE8PDE0LTIKCQloZWFkZXIgPSAyCgljYXNlIGxlbmd0aCA8IDIwOTcxNDk6IC8vIDE8PDIxIC0zCgkJaGVhZGVyID0gMwoJY2FzZSBsZW5ndGggPCAyNjg0MzU0NTI6IC8vIDE8PDI4IC00CgkJaGVhZGVyID0gNAoJZGVmYXVsdDoKCQloZWFkZXIgPSA1Cgl9CgoJcmV0dXJuIGxlbmd0aCArIGhlYWRlcgp9CgovLyBOZXdCeXRlc1F1ZXVlIGluaXRpYWxpemUgbmV3IGJ5dGVzIHF1ZXVlLgovLyBjYXBhY2l0eSBpcyB1c2VkIGluIGJ5dGVzIGFycmF5IGFsbG9jYXRpb24KLy8gV2hlbiB2ZXJib3NlIGZsYWcgaXMgc2V0IHRoZW4gaW5mb3JtYXRpb24gYWJvdXQgbWVtb3J5IGFsbG9jYXRpb24gYXJlIHByaW50ZWQKZnVuYyBOZXdCeXRlc1F1ZXVlKGNhcGFjaXR5IGludCwgbWF4Q2FwYWNpdHkgaW50LCB2ZXJib3NlIGJvb2wpICpCeXRlc1F1ZXVlIHsKCXJldHVybiAmQnl0ZXNRdWV1ZXsKCQlhcnJheTogICAgICAgIG1ha2UoW11ieXRlLCBjYXBhY2l0eSksCgkJY2FwYWNpdHk6ICAgICBjYXBhY2l0eSwKCQltYXhDYXBhY2l0eTogIG1heENhcGFjaXR5LAoJCWhlYWRlckJ1ZmZlcjogbWFrZShbXWJ5dGUsIGJpbmFyeS5NYXhWYXJpbnRMZW4zMiksCgkJdGFpbDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJaGVhZDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJcmlnaHRNYXJnaW46ICBsZWZ0TWFyZ2luSW5kZXgsCgkJdmVyYm9zZTogICAgICB2ZXJib3NlLAoJfQp9CgovLyBSZXNldCByZW1vdmVzIGFsbCBlbnRyaWVzIGZyb20gcXVldWUKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgUmVzZXQoKSB7CgkvLyBKdXN0IHJlc2V0IGluZGV4ZXMKCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJcS5oZWFkID0gbGVmdE1hcmdpbkluZGV4CglxLnJpZ2h0TWFyZ2luID0gbGVmdE1hcmdpbkluZGV4CglxLmNvdW50ID0gMAoJcS5mdWxsID0gZmFsc2UKfQoKLy8gUHVzaCBjb3BpZXMgZW50cnkgYXQgdGhlIGVuZCBvZiBxdWV1ZSBhbmQgbW92ZXMgdGFpbCBwb2ludGVyLiBBbGxvY2F0ZXMgbW9yZSBzcGFjZSBpZiBuZWVkZWQuCi8vIFJldHVybnMgaW5kZXggZm9yIHB1c2hlZCBkYXRhIG9yIGVycm9yIGlmIG1heGltdW0gc2l6ZSBxdWV1ZSBsaW1pdCBpcyByZWFjaGVkLgpmdW5jIChxICpCeXRlc1F1ZXVlKSBQdXNoKGRhdGEgW11ieXRlKSAoaW50LCBlcnJvcikgewoJbmVlZGVkU2l6ZSA6PSBnZXROZWVkZWRTaXplKGxlbihkYXRhKSkKCglpZiAhcS5jYW5JbnNlcnRBZnRlclRhaWwobmVlZGVkU2l6ZSkgewoJCWlmIHEuY2FuSW5zZXJ0QmVmb3JlSGVhZChuZWVkZWRTaXplKSB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0gZWxzZSBpZiBxLmNhcGFjaXR5K25lZWRlZFNpemUgPj0gcS5tYXhDYXBhY2l0eSAmJiBxLm1heENhcGFjaXR5ID4gMCB7CgkJCXJldHVybiAtMSwgJnF1ZXVlRXJyb3J7IkZ1bGwgcXVldWUuIE1heGltdW0gc2l6ZSBsaW1pdCByZWFjaGVkLiJ9CgkJfSBlbHNlIHsKCQkJcS5hbGxvY2F0ZUFkZGl0aW9uYWxNZW1vcnkobmVlZGVkU2l6ZSkKCQl9Cgl9CgoJaW5kZXggOj0gcS50YWlsCgoJcS5wdXNoKGRhdGEsIG5lZWRlZFNpemUpCgoJcmV0dXJuIGluZGV4LCBuaWwKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgYWxsb2NhdGVBZGRpdGlvbmFsTWVtb3J5KG1pbmltdW0gaW50KSB7CglzdGFydCA6PSB0aW1lLk5vdygpCglpZiBxLmNhcGFjaXR5IDwgbWluaW11bSB7CgkJcS5jYXBhY2l0eSArPSBtaW5pbXVtCgl9CglxLmNhcGFjaXR5ID0gcS5jYXBhY2l0eSAqIDIKCWlmIHEuY2FwYWNpdHkgPiBxLm1heENhcGFjaXR5ICYmIHEubWF4Q2FwYWNpdHkgPiAwIHsKCQlxLmNhcGFjaXR5ID0gcS5tYXhDYXBhY2l0eQoJfQoKCW9sZEFycmF5IDo9IHEuYXJyYXkKCXEuYXJyYXkgPSBtYWtlKFtdYnl0ZSwgcS5jYXBhY2l0eSkKCglpZiBsZWZ0TWFyZ2luSW5kZXggIT0gcS5yaWdodE1hcmdpbiB7CgkJY29weShxLmFycmF5LCBvbGRBcnJheVs6cS5yaWdodE1hcmdpbl0pCgoJCWlmIHEudGFpbCA8PSBxLmhlYWQgewoJCQlpZiBxLnRhaWwgIT0gcS5oZWFkIHsKCQkJCS8vIGNyZWF0ZWQgc2xpY2UgaXMgc2xpZ2h0bHkgbGFyZ2VyIHRoYW4gbmVlZCBidXQgdGhpcyBpcyBmaW5lIGFmdGVyIG9ubHkgdGhlIG5lZWRlZCBieXRlcyBhcmUgY29waWVkCgkJCQlxLnB1c2gobWFrZShbXWJ5dGUsIHEuaGVhZC1xLnRhaWwpLCBxLmhlYWQtcS50YWlsKQoJCQl9CgoJCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQkJcS50YWlsID0gcS5yaWdodE1hcmdpbgoJCX0KCX0KCglxLmZ1bGwgPSBmYWxzZQoKCWlmIHEudmVyYm9zZSB7CgkJbG9nLlByaW50ZigiQWxsb2NhdGVkIG5ldyBxdWV1ZSBpbiAlczsgQ2FwYWNpdHk6ICVkIFxuIiwgdGltZS5TaW5jZShzdGFydCksIHEuY2FwYWNpdHkpCgl9Cn0KCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIHB1c2goZGF0YSBbXWJ5dGUsIGxlbiBpbnQpIHsKCWhlYWRlckVudHJ5U2l6ZSA6PSBiaW5hcnkuUHV0VXZhcmludChxLmhlYWRlckJ1ZmZlciwgdWludDY0KGxlbikpCglxLmNvcHkocS5oZWFkZXJCdWZmZXIsIGhlYWRlckVudHJ5U2l6ZSkKCglxLmNvcHkoZGF0YSwgbGVuLWhlYWRlckVudHJ5U2l6ZSkKCglpZiBxLnRhaWwgPiBxLmhlYWQgewoJCXEucmlnaHRNYXJnaW4gPSBxLnRhaWwKCX0KCWlmIHEudGFpbCA9PSBxLmhlYWQgewoJCXEuZnVsbCA9IHRydWUKCX0KCglxLmNvdW50KysKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgY29weShkYXRhIFtdYnl0ZSwgbGVuIGludCkgewoJcS50YWlsICs9IGNvcHkocS5hcnJheVtxLnRhaWw6XSwgZGF0YVs6bGVuXSkKfQoKLy8gUG9wIHJlYWRzIHRoZSBvbGRlc3QgZW50cnkgZnJvbSBxdWV1ZSBhbmQgbW92ZXMgaGVhZCBwb2ludGVyIHRvIHRoZSBuZXh0IG9uZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBQb3AoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgYmxvY2tTaXplLCBlcnIgOj0gcS5wZWVrKHEuaGVhZCkKCWlmIGVyciAhPSBuaWwgewoJCXJldHVybiBuaWwsIGVycgoJfQoKCXEuaGVhZCArPSBibG9ja1NpemUKCXEuY291bnQtLQoKCWlmIHEuaGVhZCA9PSBxLnJpZ2h0TWFyZ2luIHsKCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQlpZiBxLnRhaWwgPT0gcS5yaWdodE1hcmdpbiB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0KCQlxLnJpZ2h0TWFyZ2luID0gcS50YWlsCgl9CgoJcS5mdWxsID0gZmFsc2UKCglyZXR1cm4gZGF0YSwgbmlsCn0KCi8vIFBlZWsgcmVhZHMgdGhlIG9sZGVzdCBlbnRyeSBmcm9tIGxpc3Qgd2l0aG91dCBtb3ZpbmcgaGVhZCBwb2ludGVyCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIFBlZWsoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgXywgZXJyIDo9IHEucGVlayhxLmhlYWQpCglyZXR1cm4gZGF0YSwgZXJyCn0KCi8vIEdldCByZWFkcyBlbnRyeSBmcm9tIGluZGV4CmZ1bmMgKHEgKkJ5dGVzUXVldWUpIEdldChpbmRleCBpbnQpIChbXWJ5dGUsIGVycm9yKSB7CglkYXRhLCBfLCBlcnIgOj0gcS5wZWVrKGluZGV4KQoJcmV0dXJuIGRhdGEsIGVycgp9CgovLyBDaGVja0dldCBjaGVja3MgaWYgYW4gZW50cnkgY2FuIGJlIHJlYWQgZnJvbSBpbmRleApmdW5jIChxICpCeXRlc1F1ZXVlKSBDaGVja0dldChpbmRleCBpbnQpIGVycm9yIHsKCXJldHVybiBxLnBlZWtDaGVja0VycihpbmRleCkKfQoKLy8gQ2FwYWNpdHkgcmV0dXJucyBudW1iZXIgb2YgYWxsb2NhdGVkIGJ5dGVzIGZvciBxdWV1ZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBDYXBhY2l0eSgpIGludCB7CglyZXR1cm4gcS5jYXBhY2l0eQp9CgovLyBMZW4gcmV0dXJucyBudW1iZXIgb2YgZW50cmllcyBrZXB0IGluIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIExlbigpIGludCB7CglyZXR1cm4gcS5jb3VudAp9CgovLyBFcnJvciByZXR1cm5zIGVycm9yIG1lc3NhZ2UKZnVuYyAoZSAqcXVldWVFcnJvcikgRXJyb3IoKSBzdHJpbmcgewoJcmV0dXJuIGUubWVzc2FnZQp9CgovLyBwZWVrQ2hlY2tFcnIgaXMgaWRlbnRpY2FsIHRvIHBlZWssIGJ1dCBkb2VzIG5vdCBhY3R1YWxseSByZXR1cm4gYW55IGRhdGEKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgcGVla0NoZWNrRXJyKGluZGV4IGludCkgZXJyb3IgewoKCWlmIHEuY291bnQgPT0gMCB7CgkJcmV0dXJuIGVyckVtcHR5UXVldWUKCX0KCglpZiBpbmRleCA8PSAwIHsKCQlyZXR1cm4gZXJySW52YWxpZEluZGV4Cgl9CgoJaWYgaW5kZXggPj0gbGVuKHEuYXJyYXkpIHsKCQlyZXR1cm4gZXJySW5kZXhPdXRPZkJvdW5kcwoJfQoJcmV0dXJuIG5pbAp9CgovLyBwZWVrIHJldHVybnMgdGhlIGRhdGEgZnJvbSBpbmRleCBhbmQgdGhlIG51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgdGhlIGxlbmd0aCBvZiB0aGUgZGF0YSBpbiB1dmFyaW50IGZvcm1hdApmdW5jIChxICpCeXRlc1F1ZXVlKSBwZWVrKGluZGV4IGludCkgKFtdYnl0ZSwgaW50LCBlcnJvcikgewoJZXJyIDo9IHEucGVla0NoZWNrRXJyKGluZGV4KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgMCwgZXJyCgl9CgoJYmxvY2tTaXplLCBuIDo9IGJpbmFyeS5VdmFyaW50KHEuYXJyYXlbaW5kZXg6XSkKCXJldHVybiBxLmFycmF5W2luZGV4K24gOiBpbmRleCtpbnQoYmxvY2tTaXplKV0sIGludChibG9ja1NpemUpLCBuaWwKfQoKLy8gY2FuSW5zZXJ0QWZ0ZXJUYWlsIHJldHVybnMgdHJ1ZSBpZiBpdCdzIHBvc3NpYmxlIHRvIGluc2VydCBhbiBlbnRyeSBvZiBzaXplIG9mIG5lZWQgYWZ0ZXIgdGhlIHRhaWwgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEFmdGVyVGFpbChuZWVkIGludCkgYm9vbCB7CglpZiBxLmZ1bGwgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgcS50YWlsID49IHEuaGVhZCB7CgkJcmV0dXJuIHEuY2FwYWNpdHktcS50YWlsID49IG5lZWQKCX0KCS8vIDEuIHRoZXJlIGlzIGV4YWN0bHkgbmVlZCBieXRlcyBiZXR3ZWVuIGhlYWQgYW5kIHRhaWwsIHNvIHdlIGRvIG5vdCBuZWVkCgkvLyB0byByZXNlcnZlIGV4dHJhIHNwYWNlIGZvciBhIHBvdGVudGlhbCBlbXB0eSBlbnRyeSB3aGVuIHJlYWxsb2MgdGhpcyBxdWV1ZQoJLy8gMi4gc3RpbGwgaGF2ZSB1bnVzZWQgc3BhY2UgYmV0d2VlbiB0YWlsIGFuZCBoZWFkLCB0aGVuIHdlIG11c3QgcmVzZXJ2ZQoJLy8gYXQgbGVhc3QgaGVhZGVyRW50cnlTaXplIGJ5dGVzIHNvIHdlIGNhbiBwdXQgYW4gZW1wdHkgZW50cnkKCXJldHVybiBxLmhlYWQtcS50YWlsID09IG5lZWQgfHwgcS5oZWFkLXEudGFpbCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCn0KCi8vIGNhbkluc2VydEJlZm9yZUhlYWQgcmV0dXJucyB0cnVlIGlmIGl0J3MgcG9zc2libGUgdG8gaW5zZXJ0IGFuIGVudHJ5IG9mIHNpemUgb2YgbmVlZCBiZWZvcmUgdGhlIGhlYWQgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEJlZm9yZUhlYWQobmVlZCBpbnQpIGJvb2wgewoJaWYgcS5mdWxsIHsKCQlyZXR1cm4gZmFsc2UKCX0KCWlmIHEudGFpbCA+PSBxLmhlYWQgewoJCXJldHVybiBxLmhlYWQtbGVmdE1hcmdpbkluZGV4ID09IG5lZWQgfHwgcS5oZWFkLWxlZnRNYXJnaW5JbmRleCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCgl9CglyZXR1cm4gcS5oZWFkLXEudGFpbCA9PSBuZWVkIHx8IHEuaGVhZC1xLnRhaWwgPj0gbmVlZCttaW5pbXVtSGVhZGVyU2l6ZQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ffaf7d0184c0ef71c16d2a6a82986c2fa0c4601 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:611f433095b4d401ac3da4767b4c4f941a13579bbb8ebfc1a3ccabad99c4bf3b" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..57b84a228e8d1b12107f3d93921e03c150e376fa --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/manifest.json @@ -0,0 +1,91 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..fbe1c832aa20abee431988570e8a515dd003c922 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__bet5fma2/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "3fb573cf7dc560df2f65e60619d9b303c7b9fed0f2db69578c292fa61d362aec", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..34dcd3116509d85023a500c9694a5d57df1c9cbb --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 1 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 1 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 2), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b123b9968f869be31e1daa0e8c3fd7d47b38df38 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/instruction.md @@ -0,0 +1,46 @@ +Cache operations fail with index out of range panic + +#### Description + +When performing cache operations, the application crashes with an "index out of range" panic. The error occurs during shard selection and appears to be related to how the shard mask is calculated. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "context" + "time" + + "github.com/allegro/bigcache/v3" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + config.Shards = 1024 + + cache, err := bigcache.New(context.Background(), config) + if err != nil { + panic(err) + } + + // This will panic with "index out of range" + cache.Set("key", []byte("value")) +} +``` + +#### Error Output + +``` +panic: runtime error: index out of range [4452171178779021548] with length 1 + +goroutine 19 [running]: +github.com/allegro/bigcache/v3.(*BigCache).getShard(...) + /testbed/bigcache.go:254 +github.com/allegro/bigcache/v3.(*BigCache).Set(0xc0000784e0, {0x5997f2, 0x3}, {0x599aaf, 0x5, 0x5}) + /testbed/bigcache.go:155 +0x93 +``` + +The panic happens when trying to access a shard with an index that's out of bounds for the shards slice. This suggests an issue with the shard mask calculation that's used to determine which shard to use for a given key. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..8acf17bfc69b6147bd80006d8f515b4ce207c22f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/provenance.json @@ -0,0 +1,372 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "bigcache.go": { + "mode": "0o644", + "sha256": "437cf63660cf373a85be54060e8974f5ab091944a77e4c2999f2c4bf79d86925", + "size": 7884 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 3, + "original_patch_sha256": "5e48c15d39b8e0ea11a8b93b731067d80321e2f2aaaa153a226a65a60af315cc", + "retained_mutation_file": "bigcache.go", + "retained_mutation_hunk_sha256": "1ecca56a9aa3ac4aaad339d25e7259bdefe071beca654d852f15c38a4b89fd86" + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "5a9b8d791dd6b8069313ca99509337cc30cb89ff2bbe53e0b538aa60706a0769", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "2bbf136aaa80cd1cbbbae9ee8baef4b73cce39ef3321283bcf82b41b1a58a54f", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "d71e9caf3d28e5086dc95a86237da4112ebded7ac1a0ffbbd76fb4b29812dd70", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "53ca360a9e514bcc3c1cf3920e94cce393fa4cd16394c92120c435ec5ded34a3", + "is_fork": true, + "learner_path": "tasks/9e94c91c2e0dda1b64aaa19c/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/d244e80ec650ae4a0aedfb577e02103eaf03a9a5/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "5e48c15d39b8e0ea11a8b93b731067d80321e2f2aaaa153a226a65a60af315cc", + "provenance_path": "tasks/9e94c91c2e0dda1b64aaa19c/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "d244e80ec650ae4a0aedfb577e02103eaf03a9a5", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "e4312370c970bbe924a6d839d0a63030c00ee7a4", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b", + "task_sha256": "b1c78c7386614d4c47c82ec97d45e3e690b2f9c40afb6c2701466dd79ccd46a5", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "0daaf81ebd39bc05f0b97d92b02742df46cfd8f29918a72b4278b1624153ae5b", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e20771b34c4feaadd38f3aa1c59b581fe4d7ea5a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bigcache.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJjb250ZXh0IgoJImVycm9ycyIKCSJ0aW1lIgopCgpjb25zdCAoCgltaW5pbXVtRW50cmllc0luU2hhcmQgPSAxMCAvLyBNaW5pbXVtIG51bWJlciBvZiBlbnRyaWVzIGluIHNpbmdsZSBzaGFyZAopCgovLyBCaWdDYWNoZSBpcyBmYXN0LCBjb25jdXJyZW50LCBldmljdGluZyBjYWNoZSBjcmVhdGVkIHRvIGtlZXAgYmlnIG51bWJlciBvZiBlbnRyaWVzIHdpdGhvdXQgaW1wYWN0IG9uIHBlcmZvcm1hbmNlLgovLyBJdCBrZWVwcyBlbnRyaWVzIG9uIGhlYXAgYnV0IG9taXRzIEdDIGZvciB0aGVtLiBUbyBhY2hpZXZlIHRoYXQsIG9wZXJhdGlvbnMgdGFrZSBwbGFjZSBvbiBieXRlIGFycmF5cywKLy8gdGhlcmVmb3JlIGVudHJpZXMgKGRlKXNlcmlhbGl6YXRpb24gaW4gZnJvbnQgb2YgdGhlIGNhY2hlIHdpbGwgYmUgbmVlZGVkIGluIG1vc3QgdXNlIGNhc2VzLgp0eXBlIEJpZ0NhY2hlIHN0cnVjdCB7CglzaGFyZHMgICAgIFtdKmNhY2hlU2hhcmQKCWxpZmVXaW5kb3cgdWludDY0CgljbG9jayAgICAgIGNsb2NrCgloYXNoICAgICAgIEhhc2hlcgoJY29uZmlnICAgICBDb25maWcKCXNoYXJkTWFzayAgdWludDY0CgljbG9zZSAgICAgIGNoYW4gc3RydWN0e30KfQoKLy8gUmVzcG9uc2Ugd2lsbCBjb250YWluIG1ldGFkYXRhIGFib3V0IHRoZSBlbnRyeSBmb3Igd2hpY2ggR2V0V2l0aEluZm8oa2V5KSB3YXMgY2FsbGVkCnR5cGUgUmVzcG9uc2Ugc3RydWN0IHsKCUVudHJ5U3RhdHVzIFJlbW92ZVJlYXNvbgp9CgovLyBSZW1vdmVSZWFzb24gaXMgYSB2YWx1ZSB1c2VkIHRvIHNpZ25hbCB0byB0aGUgdXNlciB3aHkgYSBwYXJ0aWN1bGFyIGtleSB3YXMgcmVtb3ZlZCBpbiB0aGUgT25SZW1vdmUgY2FsbGJhY2suCnR5cGUgUmVtb3ZlUmVhc29uIHVpbnQzMgoKY29uc3QgKAoJLy8gRXhwaXJlZCBtZWFucyB0aGUga2V5IGlzIHBhc3QgaXRzIExpZmVXaW5kb3cuCglFeHBpcmVkID0gUmVtb3ZlUmVhc29uKDEpCgkvLyBOb1NwYWNlIG1lYW5zIHRoZSBrZXkgaXMgdGhlIG9sZGVzdCBhbmQgdGhlIGNhY2hlIHNpemUgd2FzIGF0IGl0cyBtYXhpbXVtIHdoZW4gU2V0IHdhcyBjYWxsZWQsIG9yIHRoZQoJLy8gZW50cnkgZXhjZWVkZWQgdGhlIG1heGltdW0gc2hhcmQgc2l6ZS4KCU5vU3BhY2UgPSBSZW1vdmVSZWFzb24oMikKCS8vIERlbGV0ZWQgbWVhbnMgRGVsZXRlIHdhcyBjYWxsZWQgYW5kIHRoaXMga2V5IHdhcyByZW1vdmVkIGFzIGEgcmVzdWx0LgoJRGVsZXRlZCA9IFJlbW92ZVJlYXNvbigzKQopCgovLyBOZXcgaW5pdGlhbGl6ZSBuZXcgaW5zdGFuY2Ugb2YgQmlnQ2FjaGUKZnVuYyBOZXcoY3R4IGNvbnRleHQuQ29udGV4dCwgY29uZmlnIENvbmZpZykgKCpCaWdDYWNoZSwgZXJyb3IpIHsKCXJldHVybiBuZXdCaWdDYWNoZShjdHgsIGNvbmZpZywgJnN5c3RlbUNsb2Nre30pCn0KCi8vIE5ld0JpZ0NhY2hlIGluaXRpYWxpemUgbmV3IGluc3RhbmNlIG9mIEJpZ0NhY2hlCi8vCi8vIERlcHJlY2F0ZWQ6IE5ld0JpZ0NhY2hlIGlzIGRlcHJlY2F0ZWQsIHBsZWFzZSB1c2UgTmV3KGN0eCwgY29uZmlnKSBpbnN0ZWFkLAovLyBOZXcgdGFrZXMgaW4gY29udGV4dCBhbmQgY2FuIGdyYWNlZnVsbHkKLy8gc2h1dGRvd24gd2l0aCBjb250ZXh0IGNhbmNlbGxhdGlvbnMKZnVuYyBOZXdCaWdDYWNoZShjb25maWcgQ29uZmlnKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJcmV0dXJuIG5ld0JpZ0NhY2hlKGNvbnRleHQuQmFja2dyb3VuZCgpLCBjb25maWcsICZzeXN0ZW1DbG9ja3t9KQp9CgpmdW5jIG5ld0JpZ0NhY2hlKGN0eCBjb250ZXh0LkNvbnRleHQsIGNvbmZpZyBDb25maWcsIGNsb2NrIGNsb2NrKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJaWYgIWlzUG93ZXJPZlR3byhjb25maWcuU2hhcmRzKSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiU2hhcmRzIG51bWJlciBtdXN0IGJlIHBvd2VyIG9mIHR3byIpCgl9CglpZiBjb25maWcuTWF4RW50cnlTaXplIDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cnlTaXplIG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuTWF4RW50cmllc0luV2luZG93IDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cmllc0luV2luZG93IG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuSGFyZE1heENhY2hlU2l6ZSA8IDAgewoJCXJldHVybiBuaWwsIGVycm9ycy5OZXcoIkhhcmRNYXhDYWNoZVNpemUgbXVzdCBiZSA+PSAwIikKCX0KCglsaWZlV2luZG93U2Vjb25kcyA6PSB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKQoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCAmJiBsaWZlV2luZG93U2Vjb25kcyA9PSAwIHsKCQlyZXR1cm4gbmlsLCBlcnJvcnMuTmV3KCJMaWZlV2luZG93IG11c3QgYmUgPj0gMXMgd2hlbiBDbGVhbldpbmRvdyBpcyBzZXQiKQoJfQoKCWlmIGNvbmZpZy5IYXNoZXIgPT0gbmlsIHsKCQljb25maWcuSGFzaGVyID0gbmV3RGVmYXVsdEhhc2hlcigpCgl9CgoJY2FjaGUgOj0gJkJpZ0NhY2hlewoJCXNoYXJkczogICAgIG1ha2UoW10qY2FjaGVTaGFyZCwgY29uZmlnLlNoYXJkcyksCgkJbGlmZVdpbmRvdzogbGlmZVdpbmRvd1NlY29uZHMsCgkJY2xvY2s6ICAgICAgY2xvY2ssCgkJaGFzaDogICAgICAgY29uZmlnLkhhc2hlciwKCQljb25maWc6ICAgICBjb25maWcsCgkJc2hhcmRNYXNrOiAgdWludDY0KGNvbmZpZy5TaGFyZHMgLSAxKSwKCQljbG9zZTogICAgICBtYWtlKGNoYW4gc3RydWN0e30pLAoJfQoKCXZhciBvblJlbW92ZSBmdW5jKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pCglpZiBjb25maWcuT25SZW1vdmVXaXRoTWV0YWRhdGEgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmVXaXRoTWV0YWRhdGEKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmUgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmUKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmVXaXRoUmVhc29uICE9IG5pbCB7CgkJb25SZW1vdmUgPSBjYWNoZS5wcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbgoJfSBlbHNlIHsKCQlvblJlbW92ZSA9IGNhY2hlLm5vdFByb3ZpZGVkT25SZW1vdmUKCX0KCglmb3IgaSA6PSAwOyBpIDwgY29uZmlnLlNoYXJkczsgaSsrIHsKCQljYWNoZS5zaGFyZHNbaV0gPSBpbml0TmV3U2hhcmQoY29uZmlnLCBvblJlbW92ZSwgY2xvY2spCgl9CgoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCB7CgkJZ28gZnVuYygpIHsKCQkJdGlja2VyIDo9IHRpbWUuTmV3VGlja2VyKGNvbmZpZy5DbGVhbldpbmRvdykKCQkJZGVmZXIgdGlja2VyLlN0b3AoKQoJCQlmb3IgewoJCQkJc2VsZWN0IHsKCQkJCWNhc2UgPC1jdHguRG9uZSgpOgoJCQkJCXJldHVybgoJCQkJY2FzZSB0IDo9IDwtdGlja2VyLkM6CgkJCQkJY2FjaGUuY2xlYW5VcCh1aW50NjQodC5Vbml4KCkpKQoJCQkJY2FzZSA8LWNhY2hlLmNsb3NlOgoJCQkJCXJldHVybgoJCQkJfQoJCQl9CgkJfSgpCgl9CgoJcmV0dXJuIGNhY2hlLCBuaWwKfQoKLy8gQ2xvc2UgaXMgdXNlZCB0byBzaWduYWwgYSBzaHV0ZG93biBvZiB0aGUgY2FjaGUgd2hlbiB5b3UgYXJlIGRvbmUgd2l0aCBpdC4KLy8gVGhpcyBhbGxvd3MgdGhlIGNsZWFuaW5nIGdvcm91dGluZXMgdG8gZXhpdCBhbmQgZW5zdXJlcyByZWZlcmVuY2VzIGFyZSBub3QKLy8ga2VwdCB0byB0aGUgY2FjaGUgcHJldmVudGluZyBHQyBvZiB0aGUgZW50aXJlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2xvc2UoKSBlcnJvciB7CgljbG9zZShjLmNsb3NlKQoJcmV0dXJuIG5pbAp9CgovLyBHZXQgcmVhZHMgZW50cnkgZm9yIHRoZSBrZXkuCi8vIEl0IHJldHVybnMgYW4gRXJyRW50cnlOb3RGb3VuZCB3aGVuCi8vIG5vIGVudHJ5IGV4aXN0cyBmb3IgdGhlIGdpdmVuIGtleS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEdldChrZXkgc3RyaW5nKSAoW11ieXRlLCBlcnJvcikgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5nZXQoa2V5LCBoYXNoZWRLZXkpCn0KCi8vIEdldFdpdGhJbmZvIHJlYWRzIGVudHJ5IGZvciB0aGUga2V5IHdpdGggUmVzcG9uc2UgaW5mby4KLy8gSXQgcmV0dXJucyBhbiBFcnJFbnRyeU5vdEZvdW5kIHdoZW4KLy8gbm8gZW50cnkgZXhpc3RzIGZvciB0aGUgZ2l2ZW4ga2V5LgpmdW5jIChjICpCaWdDYWNoZSkgR2V0V2l0aEluZm8oa2V5IHN0cmluZykgKFtdYnl0ZSwgUmVzcG9uc2UsIGVycm9yKSB7CgloYXNoZWRLZXkgOj0gYy5oYXNoLlN1bTY0KGtleSkKCXNoYXJkIDo9IGMuZ2V0U2hhcmQoaGFzaGVkS2V5KQoJcmV0dXJuIHNoYXJkLmdldFdpdGhJbmZvKGtleSwgaGFzaGVkS2V5KQp9CgovLyBTZXQgc2F2ZXMgZW50cnkgdW5kZXIgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgU2V0KGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5zZXQoa2V5LCBoYXNoZWRLZXksIGVudHJ5KQp9CgovLyBBcHBlbmQgYXBwZW5kcyBlbnRyeSB1bmRlciB0aGUga2V5IGlmIGtleSBleGlzdHMsIG90aGVyd2lzZQovLyBpdCB3aWxsIHNldCB0aGUga2V5IChzYW1lIGJlaGF2aW91ciBhcyBTZXQoKSkuIFdpdGggQXBwZW5kKCkgeW91IGNhbgovLyBjb25jYXRlbmF0ZSBtdWx0aXBsZSBlbnRyaWVzIHVuZGVyIHRoZSBzYW1lIGtleSBpbiBhIGxvY2stb3B0aW1pemVkIHdheS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEFwcGVuZChrZXkgc3RyaW5nLCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuYXBwZW5kKGtleSwgaGFzaGVkS2V5LCBlbnRyeSkKfQoKLy8gRGVsZXRlIHJlbW92ZXMgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgRGVsZXRlKGtleSBzdHJpbmcpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZGVsKGhhc2hlZEtleSkKfQoKLy8gUmVzZXQgZW1wdGllcyBhbGwgY2FjaGUgc2hhcmRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldCgpIGVycm9yIHsKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJc2hhcmQucmVzZXQoYy5jb25maWcpCgl9CglyZXR1cm4gbmlsCn0KCi8vIFJlc2V0U3RhdHMgcmVzZXRzIGNhY2hlIHN0YXRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldFN0YXRzKCkgZXJyb3IgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5yZXNldFN0YXRzKCkKCX0KCXJldHVybiBuaWwKfQoKLy8gTGVuIGNvbXB1dGVzIHRoZSBudW1iZXIgb2YgZW50cmllcyBpbiB0aGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBMZW4oKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmxlbigpCgl9CglyZXR1cm4gbGVuCn0KCi8vIENhcGFjaXR5IHJldHVybnMgdGhlIGFtb3VudCBvZiBieXRlcyBzdG9yZWQgaW4gdGhlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2FwYWNpdHkoKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmNhcGFjaXR5KCkKCX0KCXJldHVybiBsZW4KfQoKLy8gU3RhdHMgcmV0dXJucyBjYWNoZSdzIHN0YXRpc3RpY3MKZnVuYyAoYyAqQmlnQ2FjaGUpIFN0YXRzKCkgU3RhdHMgewoJdmFyIHMgU3RhdHMKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJdG1wIDo9IHNoYXJkLmdldFN0YXRzKCkKCQlzLkhpdHMgKz0gdG1wLkhpdHMKCQlzLk1pc3NlcyArPSB0bXAuTWlzc2VzCgkJcy5EZWxIaXRzICs9IHRtcC5EZWxIaXRzCgkJcy5EZWxNaXNzZXMgKz0gdG1wLkRlbE1pc3NlcwoJCXMuQ29sbGlzaW9ucyArPSB0bXAuQ29sbGlzaW9ucwoJfQoJcmV0dXJuIHMKfQoKLy8gS2V5TWV0YWRhdGEgcmV0dXJucyBudW1iZXIgb2YgdGltZXMgYSBjYWNoZWQgcmVzb3VyY2Ugd2FzIHJlcXVlc3RlZC4KZnVuYyAoYyAqQmlnQ2FjaGUpIEtleU1ldGFkYXRhKGtleSBzdHJpbmcpIE1ldGFkYXRhIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZ2V0S2V5TWV0YWRhdGFXaXRoTG9jayhoYXNoZWRLZXkpCn0KCi8vIEl0ZXJhdG9yIHJldHVybnMgaXRlcmF0b3IgZnVuY3Rpb24gdG8gaXRlcmF0ZSBvdmVyIEVudHJ5SW5mbydzIGZyb20gd2hvbGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBJdGVyYXRvcigpICpFbnRyeUluZm9JdGVyYXRvciB7CglyZXR1cm4gbmV3SXRlcmF0b3IoYykKfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPCBvbGRlc3RUaW1lc3RhbXAgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgY3VycmVudFRpbWVzdGFtcC1vbGRlc3RUaW1lc3RhbXAgPiBjLmxpZmVXaW5kb3cgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChjICpCaWdDYWNoZSkgY2xlYW5VcChjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5jbGVhblVwKGN1cnJlbnRUaW1lc3RhbXApCgl9Cn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBnZXRTaGFyZChoYXNoZWRLZXkgdWludDY0KSAoc2hhcmQgKmNhY2hlU2hhcmQpIHsKCXJldHVybiBjLnNoYXJkc1toYXNoZWRLZXkmYy5zaGFyZE1hc2tdCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pIHsKCWMuY29uZmlnLk9uUmVtb3ZlKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkpCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbih3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglpZiBjLmNvbmZpZy5vblJlbW92ZUZpbHRlciA9PSAwIHx8ICgxPDx1aW50KHJlYXNvbikpJmMuY29uZmlnLm9uUmVtb3ZlRmlsdGVyID4gMCB7CgkJYy5jb25maWcuT25SZW1vdmVXaXRoUmVhc29uKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHJlYXNvbikKCX0KfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG5vdFByb3ZpZGVkT25SZW1vdmUod3JhcHBlZEVudHJ5IFtdYnl0ZSwgcmVhc29uIFJlbW92ZVJlYXNvbikgewp9CgpmdW5jIChjICpCaWdDYWNoZSkgcHJvdmlkZWRPblJlbW92ZVdpdGhNZXRhZGF0YSh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglrZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCWMuY29uZmlnLk9uUmVtb3ZlV2l0aE1ldGFkYXRhKGtleSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHNoYXJkLmdldEtleU1ldGFkYXRhKGhhc2hlZEtleSkpCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..244270af68492d18ca82f9e7b9b6e4a6ac7ffe74 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:14d2123a73915cdbebfe1f6735771b07bc95caab880b5fabc0c500c25d1e42d7" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..95ae4ef92ef069c16b2c09805306454080671404 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/manifest.json @@ -0,0 +1,256 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/partial-repair.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d3290462cf46d91017eb12ad6bc4cca3fdc04b8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bigcache.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJjb250ZXh0IgoJImVycm9ycyIKCSJ0aW1lIgopCgpjb25zdCAoCgltaW5pbXVtRW50cmllc0luU2hhcmQgPSAxMCAvLyBNaW5pbXVtIG51bWJlciBvZiBlbnRyaWVzIGluIHNpbmdsZSBzaGFyZAopCgovLyBCaWdDYWNoZSBpcyBmYXN0LCBjb25jdXJyZW50LCBldmljdGluZyBjYWNoZSBjcmVhdGVkIHRvIGtlZXAgYmlnIG51bWJlciBvZiBlbnRyaWVzIHdpdGhvdXQgaW1wYWN0IG9uIHBlcmZvcm1hbmNlLgovLyBJdCBrZWVwcyBlbnRyaWVzIG9uIGhlYXAgYnV0IG9taXRzIEdDIGZvciB0aGVtLiBUbyBhY2hpZXZlIHRoYXQsIG9wZXJhdGlvbnMgdGFrZSBwbGFjZSBvbiBieXRlIGFycmF5cywKLy8gdGhlcmVmb3JlIGVudHJpZXMgKGRlKXNlcmlhbGl6YXRpb24gaW4gZnJvbnQgb2YgdGhlIGNhY2hlIHdpbGwgYmUgbmVlZGVkIGluIG1vc3QgdXNlIGNhc2VzLgp0eXBlIEJpZ0NhY2hlIHN0cnVjdCB7CglzaGFyZHMgICAgIFtdKmNhY2hlU2hhcmQKCWxpZmVXaW5kb3cgdWludDY0CgljbG9jayAgICAgIGNsb2NrCgloYXNoICAgICAgIEhhc2hlcgoJY29uZmlnICAgICBDb25maWcKCXNoYXJkTWFzayAgdWludDY0CgljbG9zZSAgICAgIGNoYW4gc3RydWN0e30KfQoKLy8gUmVzcG9uc2Ugd2lsbCBjb250YWluIG1ldGFkYXRhIGFib3V0IHRoZSBlbnRyeSBmb3Igd2hpY2ggR2V0V2l0aEluZm8oa2V5KSB3YXMgY2FsbGVkCnR5cGUgUmVzcG9uc2Ugc3RydWN0IHsKCUVudHJ5U3RhdHVzIFJlbW92ZVJlYXNvbgp9CgovLyBSZW1vdmVSZWFzb24gaXMgYSB2YWx1ZSB1c2VkIHRvIHNpZ25hbCB0byB0aGUgdXNlciB3aHkgYSBwYXJ0aWN1bGFyIGtleSB3YXMgcmVtb3ZlZCBpbiB0aGUgT25SZW1vdmUgY2FsbGJhY2suCnR5cGUgUmVtb3ZlUmVhc29uIHVpbnQzMgoKY29uc3QgKAoJLy8gRXhwaXJlZCBtZWFucyB0aGUga2V5IGlzIHBhc3QgaXRzIExpZmVXaW5kb3cuCglFeHBpcmVkID0gUmVtb3ZlUmVhc29uKDEpCgkvLyBOb1NwYWNlIG1lYW5zIHRoZSBrZXkgaXMgdGhlIG9sZGVzdCBhbmQgdGhlIGNhY2hlIHNpemUgd2FzIGF0IGl0cyBtYXhpbXVtIHdoZW4gU2V0IHdhcyBjYWxsZWQsIG9yIHRoZQoJLy8gZW50cnkgZXhjZWVkZWQgdGhlIG1heGltdW0gc2hhcmQgc2l6ZS4KCU5vU3BhY2UgPSBSZW1vdmVSZWFzb24oMikKCS8vIERlbGV0ZWQgbWVhbnMgRGVsZXRlIHdhcyBjYWxsZWQgYW5kIHRoaXMga2V5IHdhcyByZW1vdmVkIGFzIGEgcmVzdWx0LgoJRGVsZXRlZCA9IFJlbW92ZVJlYXNvbigzKQopCgovLyBOZXcgaW5pdGlhbGl6ZSBuZXcgaW5zdGFuY2Ugb2YgQmlnQ2FjaGUKZnVuYyBOZXcoY3R4IGNvbnRleHQuQ29udGV4dCwgY29uZmlnIENvbmZpZykgKCpCaWdDYWNoZSwgZXJyb3IpIHsKCXJldHVybiBuZXdCaWdDYWNoZShjdHgsIGNvbmZpZywgJnN5c3RlbUNsb2Nre30pCn0KCi8vIE5ld0JpZ0NhY2hlIGluaXRpYWxpemUgbmV3IGluc3RhbmNlIG9mIEJpZ0NhY2hlCi8vCi8vIERlcHJlY2F0ZWQ6IE5ld0JpZ0NhY2hlIGlzIGRlcHJlY2F0ZWQsIHBsZWFzZSB1c2UgTmV3KGN0eCwgY29uZmlnKSBpbnN0ZWFkLAovLyBOZXcgdGFrZXMgaW4gY29udGV4dCBhbmQgY2FuIGdyYWNlZnVsbHkKLy8gc2h1dGRvd24gd2l0aCBjb250ZXh0IGNhbmNlbGxhdGlvbnMKZnVuYyBOZXdCaWdDYWNoZShjb25maWcgQ29uZmlnKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJcmV0dXJuIG5ld0JpZ0NhY2hlKGNvbnRleHQuQmFja2dyb3VuZCgpLCBjb25maWcsICZzeXN0ZW1DbG9ja3t9KQp9CgpmdW5jIG5ld0JpZ0NhY2hlKGN0eCBjb250ZXh0LkNvbnRleHQsIGNvbmZpZyBDb25maWcsIGNsb2NrIGNsb2NrKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJaWYgIWlzUG93ZXJPZlR3byhjb25maWcuU2hhcmRzKSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiU2hhcmRzIG51bWJlciBtdXN0IGJlIHBvd2VyIG9mIHR3byIpCgl9CglpZiBjb25maWcuTWF4RW50cnlTaXplIDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cnlTaXplIG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuTWF4RW50cmllc0luV2luZG93IDwgMSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cmllc0luV2luZG93IG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuSGFyZE1heENhY2hlU2l6ZSA8IDAgewoJCXJldHVybiBuaWwsIGVycm9ycy5OZXcoIkhhcmRNYXhDYWNoZVNpemUgbXVzdCBiZSA+PSAwIikKCX0KCglsaWZlV2luZG93U2Vjb25kcyA6PSB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKQoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCAmJiBsaWZlV2luZG93U2Vjb25kcyA9PSAwIHsKCQlyZXR1cm4gbmlsLCBlcnJvcnMuTmV3KCJMaWZlV2luZG93IG11c3QgYmUgPj0gMXMgd2hlbiBDbGVhbldpbmRvdyBpcyBzZXQiKQoJfQoKCWlmIGNvbmZpZy5IYXNoZXIgPT0gbmlsIHsKCQljb25maWcuSGFzaGVyID0gbmV3RGVmYXVsdEhhc2hlcigpCgl9CgoJY2FjaGUgOj0gJkJpZ0NhY2hlewoJCXNoYXJkczogICAgIG1ha2UoW10qY2FjaGVTaGFyZCwgY29uZmlnLlNoYXJkcyksCgkJbGlmZVdpbmRvdzogbGlmZVdpbmRvd1NlY29uZHMsCgkJY2xvY2s6ICAgICAgY2xvY2ssCgkJaGFzaDogICAgICAgY29uZmlnLkhhc2hlciwKCQljb25maWc6ICAgICBjb25maWcsCgkJc2hhcmRNYXNrOiAgdWludDY0KGNvbmZpZy5TaGFyZHMgLSAxKSwKCQljbG9zZTogICAgICBtYWtlKGNoYW4gc3RydWN0e30pLAoJfQoKCXZhciBvblJlbW92ZSBmdW5jKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pCglpZiBjb25maWcuT25SZW1vdmVXaXRoTWV0YWRhdGEgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmVXaXRoTWV0YWRhdGEKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmUgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmUKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmVXaXRoUmVhc29uICE9IG5pbCB7CgkJb25SZW1vdmUgPSBjYWNoZS5wcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbgoJfSBlbHNlIHsKCQlvblJlbW92ZSA9IGNhY2hlLm5vdFByb3ZpZGVkT25SZW1vdmUKCX0KCglmb3IgaSA6PSAwOyBpIDwgY29uZmlnLlNoYXJkczsgaSsrIHsKCQljYWNoZS5zaGFyZHNbaV0gPSBpbml0TmV3U2hhcmQoY29uZmlnLCBvblJlbW92ZSwgY2xvY2spCgl9CgoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCB7CgkJZ28gZnVuYygpIHsKCQkJdGlja2VyIDo9IHRpbWUuTmV3VGlja2VyKGNvbmZpZy5DbGVhbldpbmRvdykKCQkJZGVmZXIgdGlja2VyLlN0b3AoKQoJCQlmb3IgewoJCQkJc2VsZWN0IHsKCQkJCWNhc2UgPC1jdHguRG9uZSgpOgoJCQkJCXJldHVybgoJCQkJY2FzZSB0IDo9IDwtdGlja2VyLkM6CgkJCQkJY2FjaGUuY2xlYW5VcCh1aW50NjQodC5Vbml4KCkpKQoJCQkJY2FzZSA8LWNhY2hlLmNsb3NlOgoJCQkJCXJldHVybgoJCQkJfQoJCQl9CgkJfSgpCgl9CgoJcmV0dXJuIGNhY2hlLCBuaWwKfQoKLy8gQ2xvc2UgaXMgdXNlZCB0byBzaWduYWwgYSBzaHV0ZG93biBvZiB0aGUgY2FjaGUgd2hlbiB5b3UgYXJlIGRvbmUgd2l0aCBpdC4KLy8gVGhpcyBhbGxvd3MgdGhlIGNsZWFuaW5nIGdvcm91dGluZXMgdG8gZXhpdCBhbmQgZW5zdXJlcyByZWZlcmVuY2VzIGFyZSBub3QKLy8ga2VwdCB0byB0aGUgY2FjaGUgcHJldmVudGluZyBHQyBvZiB0aGUgZW50aXJlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2xvc2UoKSBlcnJvciB7CgljbG9zZShjLmNsb3NlKQoJcmV0dXJuIG5pbAp9CgovLyBHZXQgcmVhZHMgZW50cnkgZm9yIHRoZSBrZXkuCi8vIEl0IHJldHVybnMgYW4gRXJyRW50cnlOb3RGb3VuZCB3aGVuCi8vIG5vIGVudHJ5IGV4aXN0cyBmb3IgdGhlIGdpdmVuIGtleS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEdldChrZXkgc3RyaW5nKSAoW11ieXRlLCBlcnJvcikgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5nZXQoa2V5LCBoYXNoZWRLZXkpCn0KCi8vIEdldFdpdGhJbmZvIHJlYWRzIGVudHJ5IGZvciB0aGUga2V5IHdpdGggUmVzcG9uc2UgaW5mby4KLy8gSXQgcmV0dXJucyBhbiBFcnJFbnRyeU5vdEZvdW5kIHdoZW4KLy8gbm8gZW50cnkgZXhpc3RzIGZvciB0aGUgZ2l2ZW4ga2V5LgpmdW5jIChjICpCaWdDYWNoZSkgR2V0V2l0aEluZm8oa2V5IHN0cmluZykgKFtdYnl0ZSwgUmVzcG9uc2UsIGVycm9yKSB7CgloYXNoZWRLZXkgOj0gYy5oYXNoLlN1bTY0KGtleSkKCXNoYXJkIDo9IGMuZ2V0U2hhcmQoaGFzaGVkS2V5KQoJcmV0dXJuIHNoYXJkLmdldFdpdGhJbmZvKGtleSwgaGFzaGVkS2V5KQp9CgovLyBTZXQgc2F2ZXMgZW50cnkgdW5kZXIgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgU2V0KGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5zZXQoa2V5LCBoYXNoZWRLZXksIGVudHJ5KQp9CgovLyBBcHBlbmQgYXBwZW5kcyBlbnRyeSB1bmRlciB0aGUga2V5IGlmIGtleSBleGlzdHMsIG90aGVyd2lzZQovLyBpdCB3aWxsIHNldCB0aGUga2V5IChzYW1lIGJlaGF2aW91ciBhcyBTZXQoKSkuIFdpdGggQXBwZW5kKCkgeW91IGNhbgovLyBjb25jYXRlbmF0ZSBtdWx0aXBsZSBlbnRyaWVzIHVuZGVyIHRoZSBzYW1lIGtleSBpbiBhIGxvY2stb3B0aW1pemVkIHdheS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEFwcGVuZChrZXkgc3RyaW5nLCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuYXBwZW5kKGtleSwgaGFzaGVkS2V5LCBlbnRyeSkKfQoKLy8gRGVsZXRlIHJlbW92ZXMgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgRGVsZXRlKGtleSBzdHJpbmcpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZGVsKGhhc2hlZEtleSkKfQoKLy8gUmVzZXQgZW1wdGllcyBhbGwgY2FjaGUgc2hhcmRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldCgpIGVycm9yIHsKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJc2hhcmQucmVzZXQoYy5jb25maWcpCgl9CglyZXR1cm4gbmlsCn0KCi8vIFJlc2V0U3RhdHMgcmVzZXRzIGNhY2hlIHN0YXRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldFN0YXRzKCkgZXJyb3IgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5yZXNldFN0YXRzKCkKCX0KCXJldHVybiBuaWwKfQoKLy8gTGVuIGNvbXB1dGVzIHRoZSBudW1iZXIgb2YgZW50cmllcyBpbiB0aGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBMZW4oKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmxlbigpCgl9CglyZXR1cm4gbGVuCn0KCi8vIENhcGFjaXR5IHJldHVybnMgdGhlIGFtb3VudCBvZiBieXRlcyBzdG9yZWQgaW4gdGhlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2FwYWNpdHkoKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmNhcGFjaXR5KCkKCX0KCXJldHVybiBsZW4KfQoKLy8gU3RhdHMgcmV0dXJucyBjYWNoZSdzIHN0YXRpc3RpY3MKZnVuYyAoYyAqQmlnQ2FjaGUpIFN0YXRzKCkgU3RhdHMgewoJdmFyIHMgU3RhdHMKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJdG1wIDo9IHNoYXJkLmdldFN0YXRzKCkKCQlzLkhpdHMgKz0gdG1wLkhpdHMKCQlzLk1pc3NlcyArPSB0bXAuTWlzc2VzCgkJcy5EZWxIaXRzICs9IHRtcC5EZWxIaXRzCgkJcy5EZWxNaXNzZXMgKz0gdG1wLkRlbE1pc3NlcwoJCXMuQ29sbGlzaW9ucyArPSB0bXAuQ29sbGlzaW9ucwoJfQoJcmV0dXJuIHMKfQoKLy8gS2V5TWV0YWRhdGEgcmV0dXJucyBudW1iZXIgb2YgdGltZXMgYSBjYWNoZWQgcmVzb3VyY2Ugd2FzIHJlcXVlc3RlZC4KZnVuYyAoYyAqQmlnQ2FjaGUpIEtleU1ldGFkYXRhKGtleSBzdHJpbmcpIE1ldGFkYXRhIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZ2V0S2V5TWV0YWRhdGFXaXRoTG9jayhoYXNoZWRLZXkpCn0KCi8vIEl0ZXJhdG9yIHJldHVybnMgaXRlcmF0b3IgZnVuY3Rpb24gdG8gaXRlcmF0ZSBvdmVyIEVudHJ5SW5mbydzIGZyb20gd2hvbGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBJdGVyYXRvcigpICpFbnRyeUluZm9JdGVyYXRvciB7CglyZXR1cm4gbmV3SXRlcmF0b3IoYykKfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPCBvbGRlc3RUaW1lc3RhbXAgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgY3VycmVudFRpbWVzdGFtcC1vbGRlc3RUaW1lc3RhbXAgPiBjLmxpZmVXaW5kb3cgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChjICpCaWdDYWNoZSkgY2xlYW5VcChjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5jbGVhblVwKGN1cnJlbnRUaW1lc3RhbXApCgl9Cn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBnZXRTaGFyZChoYXNoZWRLZXkgdWludDY0KSAoc2hhcmQgKmNhY2hlU2hhcmQpIHsKCXJldHVybiBjLnNoYXJkc1toYXNoZWRLZXkmYy5zaGFyZE1hc2tdCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pIHsKCWMuY29uZmlnLk9uUmVtb3ZlKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkpCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbih3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglpZiBjLmNvbmZpZy5vblJlbW92ZUZpbHRlciA9PSAwIHx8ICgxPDx1aW50KHJlYXNvbikpJmMuY29uZmlnLm9uUmVtb3ZlRmlsdGVyID4gMCB7CgkJYy5jb25maWcuT25SZW1vdmVXaXRoUmVhc29uKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHJlYXNvbikKCX0KfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG5vdFByb3ZpZGVkT25SZW1vdmUod3JhcHBlZEVudHJ5IFtdYnl0ZSwgcmVhc29uIFJlbW92ZVJlYXNvbikgewp9CgpmdW5jIChjICpCaWdDYWNoZSkgcHJvdmlkZWRPblJlbW92ZVdpdGhNZXRhZGF0YSh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglrZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCWMuY29uZmlnLk9uUmVtb3ZlV2l0aE1ldGFkYXRhKGtleSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHNoYXJkLmdldEtleU1ldGFkYXRhKGhhc2hlZEtleSkpCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..9261c5bc42800ab6582af69d8aa7b0e02b678ce7 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__r6c55t0b/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "a76f41746f6d4d245455ef540d28b5c6f1bc316d43a4efcf1c6695385247500f", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..1b2eca6ea46ca3306009fdef39730b8a83acfb03 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == -1 || (1< -1 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e166e2bb2959a09092adbdc58bc5b68a745e9e32 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/instruction.md @@ -0,0 +1,41 @@ +OnRemoveFilter not working correctly with bitwise operations + +#### Description + +The OnRemoveFilter functionality appears to be broken when using bitwise filtering for removal reasons. When setting up a filter to only trigger callbacks for specific removal reasons, the callback is being invoked for all removal reasons instead of respecting the filter. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "time" + "github.com/allegro/bigcache/v3" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + + // Set up filter to only trigger on expired entries + config.OnRemoveFilter = 1 << uint(bigcache.Expired) + config.OnRemoveWithReason = func(key string, entry []byte, reason bigcache.RemoveReason) { + fmt.Printf("Callback triggered for key: %s, reason: %v\n", key, reason) + } + + cache, _ := bigcache.NewBigCache(config) + + // Add an entry + cache.Set("test", []byte("value")) + + // Delete the entry (should NOT trigger callback since we only want Expired) + cache.Delete("test") + + // Expected: No callback output + // Actual: Callback is triggered even though reason is not Expired +} +``` + +The callback should only be invoked when entries are removed due to expiration, but it's being called for all removal operations regardless of the filter setting. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..4f28a9ffab0cb5040b5497141cd33554ed35db80 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "f5a0df7f2de73bd3cb0871460386e4cf5689d0d6a3ae4494ce78bc9d328870c4", + "size": 7886 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "production/runtime-images-v1/resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "2dff0f2f961ee4fa0cfb9a0568bf32b797bf1235cd5a792a63fc612db7e27fa6", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "22ea4ded01bdef648030eb37300a175d3a7620cc7b5b357ebd4b89deac552dcb", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "8e200cd78f23e238a0286e1581ce53ecd20d5bf819b1be61cf573faedf3c9a73", + "is_fork": true, + "learner_path": "tasks/23fee9ae995419e87038fab6/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/afe7852e89402cc793c21d109f1f9dc590f176c3/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "3c50c5ce747b7cae634cf3eda60a43df18ee7e6531794ff09de5ee3c78e9b636", + "provenance_path": "tasks/23fee9ae995419e87038fab6/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "afe7852e89402cc793c21d109f1f9dc590f176c3", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "2fea80a73b110d40ad3de10d23a6208203817c1c", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47", + "task_sha256": "8ac87933c6a24286febd4b18284dc2600d83c9ddf0d858637e6910bca6e1e91d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "0a17e23bc679bc8e3a0f6f32fc779fa196ac1a939d87366aaf60fae86529ee19", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e20771b34c4feaadd38f3aa1c59b581fe4d7ea5a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bigcache.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJjb250ZXh0IgoJImVycm9ycyIKCSJ0aW1lIgopCgpjb25zdCAoCgltaW5pbXVtRW50cmllc0luU2hhcmQgPSAxMCAvLyBNaW5pbXVtIG51bWJlciBvZiBlbnRyaWVzIGluIHNpbmdsZSBzaGFyZAopCgovLyBCaWdDYWNoZSBpcyBmYXN0LCBjb25jdXJyZW50LCBldmljdGluZyBjYWNoZSBjcmVhdGVkIHRvIGtlZXAgYmlnIG51bWJlciBvZiBlbnRyaWVzIHdpdGhvdXQgaW1wYWN0IG9uIHBlcmZvcm1hbmNlLgovLyBJdCBrZWVwcyBlbnRyaWVzIG9uIGhlYXAgYnV0IG9taXRzIEdDIGZvciB0aGVtLiBUbyBhY2hpZXZlIHRoYXQsIG9wZXJhdGlvbnMgdGFrZSBwbGFjZSBvbiBieXRlIGFycmF5cywKLy8gdGhlcmVmb3JlIGVudHJpZXMgKGRlKXNlcmlhbGl6YXRpb24gaW4gZnJvbnQgb2YgdGhlIGNhY2hlIHdpbGwgYmUgbmVlZGVkIGluIG1vc3QgdXNlIGNhc2VzLgp0eXBlIEJpZ0NhY2hlIHN0cnVjdCB7CglzaGFyZHMgICAgIFtdKmNhY2hlU2hhcmQKCWxpZmVXaW5kb3cgdWludDY0CgljbG9jayAgICAgIGNsb2NrCgloYXNoICAgICAgIEhhc2hlcgoJY29uZmlnICAgICBDb25maWcKCXNoYXJkTWFzayAgdWludDY0CgljbG9zZSAgICAgIGNoYW4gc3RydWN0e30KfQoKLy8gUmVzcG9uc2Ugd2lsbCBjb250YWluIG1ldGFkYXRhIGFib3V0IHRoZSBlbnRyeSBmb3Igd2hpY2ggR2V0V2l0aEluZm8oa2V5KSB3YXMgY2FsbGVkCnR5cGUgUmVzcG9uc2Ugc3RydWN0IHsKCUVudHJ5U3RhdHVzIFJlbW92ZVJlYXNvbgp9CgovLyBSZW1vdmVSZWFzb24gaXMgYSB2YWx1ZSB1c2VkIHRvIHNpZ25hbCB0byB0aGUgdXNlciB3aHkgYSBwYXJ0aWN1bGFyIGtleSB3YXMgcmVtb3ZlZCBpbiB0aGUgT25SZW1vdmUgY2FsbGJhY2suCnR5cGUgUmVtb3ZlUmVhc29uIHVpbnQzMgoKY29uc3QgKAoJLy8gRXhwaXJlZCBtZWFucyB0aGUga2V5IGlzIHBhc3QgaXRzIExpZmVXaW5kb3cuCglFeHBpcmVkID0gUmVtb3ZlUmVhc29uKDEpCgkvLyBOb1NwYWNlIG1lYW5zIHRoZSBrZXkgaXMgdGhlIG9sZGVzdCBhbmQgdGhlIGNhY2hlIHNpemUgd2FzIGF0IGl0cyBtYXhpbXVtIHdoZW4gU2V0IHdhcyBjYWxsZWQsIG9yIHRoZQoJLy8gZW50cnkgZXhjZWVkZWQgdGhlIG1heGltdW0gc2hhcmQgc2l6ZS4KCU5vU3BhY2UgPSBSZW1vdmVSZWFzb24oMikKCS8vIERlbGV0ZWQgbWVhbnMgRGVsZXRlIHdhcyBjYWxsZWQgYW5kIHRoaXMga2V5IHdhcyByZW1vdmVkIGFzIGEgcmVzdWx0LgoJRGVsZXRlZCA9IFJlbW92ZVJlYXNvbigzKQopCgovLyBOZXcgaW5pdGlhbGl6ZSBuZXcgaW5zdGFuY2Ugb2YgQmlnQ2FjaGUKZnVuYyBOZXcoY3R4IGNvbnRleHQuQ29udGV4dCwgY29uZmlnIENvbmZpZykgKCpCaWdDYWNoZSwgZXJyb3IpIHsKCXJldHVybiBuZXdCaWdDYWNoZShjdHgsIGNvbmZpZywgJnN5c3RlbUNsb2Nre30pCn0KCi8vIE5ld0JpZ0NhY2hlIGluaXRpYWxpemUgbmV3IGluc3RhbmNlIG9mIEJpZ0NhY2hlCi8vCi8vIERlcHJlY2F0ZWQ6IE5ld0JpZ0NhY2hlIGlzIGRlcHJlY2F0ZWQsIHBsZWFzZSB1c2UgTmV3KGN0eCwgY29uZmlnKSBpbnN0ZWFkLAovLyBOZXcgdGFrZXMgaW4gY29udGV4dCBhbmQgY2FuIGdyYWNlZnVsbHkKLy8gc2h1dGRvd24gd2l0aCBjb250ZXh0IGNhbmNlbGxhdGlvbnMKZnVuYyBOZXdCaWdDYWNoZShjb25maWcgQ29uZmlnKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJcmV0dXJuIG5ld0JpZ0NhY2hlKGNvbnRleHQuQmFja2dyb3VuZCgpLCBjb25maWcsICZzeXN0ZW1DbG9ja3t9KQp9CgpmdW5jIG5ld0JpZ0NhY2hlKGN0eCBjb250ZXh0LkNvbnRleHQsIGNvbmZpZyBDb25maWcsIGNsb2NrIGNsb2NrKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJaWYgIWlzUG93ZXJPZlR3byhjb25maWcuU2hhcmRzKSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiU2hhcmRzIG51bWJlciBtdXN0IGJlIHBvd2VyIG9mIHR3byIpCgl9CglpZiBjb25maWcuTWF4RW50cnlTaXplIDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cnlTaXplIG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuTWF4RW50cmllc0luV2luZG93IDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cmllc0luV2luZG93IG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuSGFyZE1heENhY2hlU2l6ZSA8IDAgewoJCXJldHVybiBuaWwsIGVycm9ycy5OZXcoIkhhcmRNYXhDYWNoZVNpemUgbXVzdCBiZSA+PSAwIikKCX0KCglsaWZlV2luZG93U2Vjb25kcyA6PSB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKQoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCAmJiBsaWZlV2luZG93U2Vjb25kcyA9PSAwIHsKCQlyZXR1cm4gbmlsLCBlcnJvcnMuTmV3KCJMaWZlV2luZG93IG11c3QgYmUgPj0gMXMgd2hlbiBDbGVhbldpbmRvdyBpcyBzZXQiKQoJfQoKCWlmIGNvbmZpZy5IYXNoZXIgPT0gbmlsIHsKCQljb25maWcuSGFzaGVyID0gbmV3RGVmYXVsdEhhc2hlcigpCgl9CgoJY2FjaGUgOj0gJkJpZ0NhY2hlewoJCXNoYXJkczogICAgIG1ha2UoW10qY2FjaGVTaGFyZCwgY29uZmlnLlNoYXJkcyksCgkJbGlmZVdpbmRvdzogbGlmZVdpbmRvd1NlY29uZHMsCgkJY2xvY2s6ICAgICAgY2xvY2ssCgkJaGFzaDogICAgICAgY29uZmlnLkhhc2hlciwKCQljb25maWc6ICAgICBjb25maWcsCgkJc2hhcmRNYXNrOiAgdWludDY0KGNvbmZpZy5TaGFyZHMgLSAxKSwKCQljbG9zZTogICAgICBtYWtlKGNoYW4gc3RydWN0e30pLAoJfQoKCXZhciBvblJlbW92ZSBmdW5jKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pCglpZiBjb25maWcuT25SZW1vdmVXaXRoTWV0YWRhdGEgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmVXaXRoTWV0YWRhdGEKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmUgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmUKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmVXaXRoUmVhc29uICE9IG5pbCB7CgkJb25SZW1vdmUgPSBjYWNoZS5wcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbgoJfSBlbHNlIHsKCQlvblJlbW92ZSA9IGNhY2hlLm5vdFByb3ZpZGVkT25SZW1vdmUKCX0KCglmb3IgaSA6PSAwOyBpIDwgY29uZmlnLlNoYXJkczsgaSsrIHsKCQljYWNoZS5zaGFyZHNbaV0gPSBpbml0TmV3U2hhcmQoY29uZmlnLCBvblJlbW92ZSwgY2xvY2spCgl9CgoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCB7CgkJZ28gZnVuYygpIHsKCQkJdGlja2VyIDo9IHRpbWUuTmV3VGlja2VyKGNvbmZpZy5DbGVhbldpbmRvdykKCQkJZGVmZXIgdGlja2VyLlN0b3AoKQoJCQlmb3IgewoJCQkJc2VsZWN0IHsKCQkJCWNhc2UgPC1jdHguRG9uZSgpOgoJCQkJCXJldHVybgoJCQkJY2FzZSB0IDo9IDwtdGlja2VyLkM6CgkJCQkJY2FjaGUuY2xlYW5VcCh1aW50NjQodC5Vbml4KCkpKQoJCQkJY2FzZSA8LWNhY2hlLmNsb3NlOgoJCQkJCXJldHVybgoJCQkJfQoJCQl9CgkJfSgpCgl9CgoJcmV0dXJuIGNhY2hlLCBuaWwKfQoKLy8gQ2xvc2UgaXMgdXNlZCB0byBzaWduYWwgYSBzaHV0ZG93biBvZiB0aGUgY2FjaGUgd2hlbiB5b3UgYXJlIGRvbmUgd2l0aCBpdC4KLy8gVGhpcyBhbGxvd3MgdGhlIGNsZWFuaW5nIGdvcm91dGluZXMgdG8gZXhpdCBhbmQgZW5zdXJlcyByZWZlcmVuY2VzIGFyZSBub3QKLy8ga2VwdCB0byB0aGUgY2FjaGUgcHJldmVudGluZyBHQyBvZiB0aGUgZW50aXJlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2xvc2UoKSBlcnJvciB7CgljbG9zZShjLmNsb3NlKQoJcmV0dXJuIG5pbAp9CgovLyBHZXQgcmVhZHMgZW50cnkgZm9yIHRoZSBrZXkuCi8vIEl0IHJldHVybnMgYW4gRXJyRW50cnlOb3RGb3VuZCB3aGVuCi8vIG5vIGVudHJ5IGV4aXN0cyBmb3IgdGhlIGdpdmVuIGtleS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEdldChrZXkgc3RyaW5nKSAoW11ieXRlLCBlcnJvcikgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5nZXQoa2V5LCBoYXNoZWRLZXkpCn0KCi8vIEdldFdpdGhJbmZvIHJlYWRzIGVudHJ5IGZvciB0aGUga2V5IHdpdGggUmVzcG9uc2UgaW5mby4KLy8gSXQgcmV0dXJucyBhbiBFcnJFbnRyeU5vdEZvdW5kIHdoZW4KLy8gbm8gZW50cnkgZXhpc3RzIGZvciB0aGUgZ2l2ZW4ga2V5LgpmdW5jIChjICpCaWdDYWNoZSkgR2V0V2l0aEluZm8oa2V5IHN0cmluZykgKFtdYnl0ZSwgUmVzcG9uc2UsIGVycm9yKSB7CgloYXNoZWRLZXkgOj0gYy5oYXNoLlN1bTY0KGtleSkKCXNoYXJkIDo9IGMuZ2V0U2hhcmQoaGFzaGVkS2V5KQoJcmV0dXJuIHNoYXJkLmdldFdpdGhJbmZvKGtleSwgaGFzaGVkS2V5KQp9CgovLyBTZXQgc2F2ZXMgZW50cnkgdW5kZXIgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgU2V0KGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5zZXQoa2V5LCBoYXNoZWRLZXksIGVudHJ5KQp9CgovLyBBcHBlbmQgYXBwZW5kcyBlbnRyeSB1bmRlciB0aGUga2V5IGlmIGtleSBleGlzdHMsIG90aGVyd2lzZQovLyBpdCB3aWxsIHNldCB0aGUga2V5IChzYW1lIGJlaGF2aW91ciBhcyBTZXQoKSkuIFdpdGggQXBwZW5kKCkgeW91IGNhbgovLyBjb25jYXRlbmF0ZSBtdWx0aXBsZSBlbnRyaWVzIHVuZGVyIHRoZSBzYW1lIGtleSBpbiBhIGxvY2stb3B0aW1pemVkIHdheS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEFwcGVuZChrZXkgc3RyaW5nLCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuYXBwZW5kKGtleSwgaGFzaGVkS2V5LCBlbnRyeSkKfQoKLy8gRGVsZXRlIHJlbW92ZXMgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgRGVsZXRlKGtleSBzdHJpbmcpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZGVsKGhhc2hlZEtleSkKfQoKLy8gUmVzZXQgZW1wdGllcyBhbGwgY2FjaGUgc2hhcmRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldCgpIGVycm9yIHsKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJc2hhcmQucmVzZXQoYy5jb25maWcpCgl9CglyZXR1cm4gbmlsCn0KCi8vIFJlc2V0U3RhdHMgcmVzZXRzIGNhY2hlIHN0YXRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldFN0YXRzKCkgZXJyb3IgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5yZXNldFN0YXRzKCkKCX0KCXJldHVybiBuaWwKfQoKLy8gTGVuIGNvbXB1dGVzIHRoZSBudW1iZXIgb2YgZW50cmllcyBpbiB0aGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBMZW4oKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmxlbigpCgl9CglyZXR1cm4gbGVuCn0KCi8vIENhcGFjaXR5IHJldHVybnMgdGhlIGFtb3VudCBvZiBieXRlcyBzdG9yZWQgaW4gdGhlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2FwYWNpdHkoKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmNhcGFjaXR5KCkKCX0KCXJldHVybiBsZW4KfQoKLy8gU3RhdHMgcmV0dXJucyBjYWNoZSdzIHN0YXRpc3RpY3MKZnVuYyAoYyAqQmlnQ2FjaGUpIFN0YXRzKCkgU3RhdHMgewoJdmFyIHMgU3RhdHMKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJdG1wIDo9IHNoYXJkLmdldFN0YXRzKCkKCQlzLkhpdHMgKz0gdG1wLkhpdHMKCQlzLk1pc3NlcyArPSB0bXAuTWlzc2VzCgkJcy5EZWxIaXRzICs9IHRtcC5EZWxIaXRzCgkJcy5EZWxNaXNzZXMgKz0gdG1wLkRlbE1pc3NlcwoJCXMuQ29sbGlzaW9ucyArPSB0bXAuQ29sbGlzaW9ucwoJfQoJcmV0dXJuIHMKfQoKLy8gS2V5TWV0YWRhdGEgcmV0dXJucyBudW1iZXIgb2YgdGltZXMgYSBjYWNoZWQgcmVzb3VyY2Ugd2FzIHJlcXVlc3RlZC4KZnVuYyAoYyAqQmlnQ2FjaGUpIEtleU1ldGFkYXRhKGtleSBzdHJpbmcpIE1ldGFkYXRhIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZ2V0S2V5TWV0YWRhdGFXaXRoTG9jayhoYXNoZWRLZXkpCn0KCi8vIEl0ZXJhdG9yIHJldHVybnMgaXRlcmF0b3IgZnVuY3Rpb24gdG8gaXRlcmF0ZSBvdmVyIEVudHJ5SW5mbydzIGZyb20gd2hvbGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBJdGVyYXRvcigpICpFbnRyeUluZm9JdGVyYXRvciB7CglyZXR1cm4gbmV3SXRlcmF0b3IoYykKfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPCBvbGRlc3RUaW1lc3RhbXAgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgY3VycmVudFRpbWVzdGFtcC1vbGRlc3RUaW1lc3RhbXAgPiBjLmxpZmVXaW5kb3cgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChjICpCaWdDYWNoZSkgY2xlYW5VcChjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5jbGVhblVwKGN1cnJlbnRUaW1lc3RhbXApCgl9Cn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBnZXRTaGFyZChoYXNoZWRLZXkgdWludDY0KSAoc2hhcmQgKmNhY2hlU2hhcmQpIHsKCXJldHVybiBjLnNoYXJkc1toYXNoZWRLZXkmYy5zaGFyZE1hc2tdCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pIHsKCWMuY29uZmlnLk9uUmVtb3ZlKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkpCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbih3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglpZiBjLmNvbmZpZy5vblJlbW92ZUZpbHRlciA9PSAwIHx8ICgxPDx1aW50KHJlYXNvbikpJmMuY29uZmlnLm9uUmVtb3ZlRmlsdGVyID4gMCB7CgkJYy5jb25maWcuT25SZW1vdmVXaXRoUmVhc29uKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHJlYXNvbikKCX0KfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG5vdFByb3ZpZGVkT25SZW1vdmUod3JhcHBlZEVudHJ5IFtdYnl0ZSwgcmVhc29uIFJlbW92ZVJlYXNvbikgewp9CgpmdW5jIChjICpCaWdDYWNoZSkgcHJvdmlkZWRPblJlbW92ZVdpdGhNZXRhZGF0YSh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglrZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCWMuY29uZmlnLk9uUmVtb3ZlV2l0aE1ldGFkYXRhKGtleSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHNoYXJkLmdldEtleU1ldGFkYXRhKGhhc2hlZEtleSkpCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4fa37d33ba87934126638f87ed664bf9f9988ad8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:01c3181e7dbeada7f997714c884cce11305c09528264f1adcbbd8bebc72c7ab8" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..fa90ff84ed7c576d6b9e4e1e2aeadc71bd67e744 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/manifest.json @@ -0,0 +1,561 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfoCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotPresent" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNilValueCaching" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithMostShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorInInvalidState" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithAllShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithConcurrentUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestHashCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Before_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/After_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryBiggerThanMaxShardSizeError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRetrievingEntryShouldCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestGetOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOldestEntryDeletionWhenMaxCacheSizeIsReached" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestIterateOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveGetEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveEntriesWhenShardIsFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveWithReasonCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheRestStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/Shards_number_must_be_power_of_two" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntriesInWindow_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntrySize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/HardMaxCacheSize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEviction" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotFound" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEvictionShouldEvictOnlyFromUpdatedShard" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_allocateAdditionalMemoryLeadPanic" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIterator" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestConstructCacheWithDefaultHasher" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDel" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndReadParallelSameKeyWithStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheInitialCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDelRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCleanShouldEvictAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestParallelSetAndIteration" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example_custom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..cbf59dc9ba4229c9c1e0d342f1131fe27927ebb8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_change_const__s6lash47/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "8a452cc4b54c49a7dfc7c678464c6ad98a16643455ce3299a9242d3d1df5b9e4", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..2bb4a287e2248e84272fb50aeb56a97cf71d9dca --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if len(*buffer) > blobLength { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[keyLength + headersSizeInBytes:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9b85fb9a814da0d4052893dfb4d52ab920dbedf0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/instruction.md @@ -0,0 +1,25 @@ +Buffer allocation logic inverted causing slice bounds panic + +When setting cache entries, the buffer allocation condition is inverted, causing the system to allocate a new buffer when it shouldn't and use an undersized buffer when it should allocate a larger one. This leads to slice bounds out of range panics when trying to write data that exceeds the buffer capacity. + +#### Steps to Reproduce + +```go +package main + +import ( + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + cache, _ := bigcache.NewBigCache(config) + + // This will panic with slice bounds out of range + cache.Set("test", []byte("value")) +} +``` + +The panic occurs in the `wrapEntry` function where the buffer size check is backwards, causing attempts to write beyond the allocated buffer capacity. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..0f5f9f0576a62e87d252e85e59b8be1d59d040c0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/provenance.json @@ -0,0 +1,372 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "encoding.go": { + "mode": "0o644", + "sha256": "8a0d82af1dae8fa2fa15c2d7c4482141ea9b8f36d4bc1aea56f0d43b9a6e3aa5", + "size": 2629 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 2, + "original_patch_sha256": "839802d8d31d121a8a2f2107e2c4fe195148b891c28ee16454f51b1d40d073e1", + "retained_mutation_file": "encoding.go", + "retained_mutation_hunk_sha256": "d4575e0631bfd7ac1e4dd0676d731e7eba963a76b1623f2e8b2161495194df4f" + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "0b9daf5b4a112c31bb622d528bbaae44549aa91d23d4bf4441785e8c89065827", + "size": 2631 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "52ae609ea2ff9f6f6dde759b09e860afb64893248df6c6736aafdb6413340017", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "8b7f306e1817b072376dd1fe83f5794eb64cae756945739b36a3595e7d673ac4", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "daec17e2b61a02251e420864faa3acf14c4fb5cfdcb62880e6bc35bb4bdd4986", + "is_fork": true, + "learner_path": "tasks/b957ee230d748ac87a9bf7d1/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/f360215571c20caa64e358d00a2c49e7e756c9e7/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "839802d8d31d121a8a2f2107e2c4fe195148b891c28ee16454f51b1d40d073e1", + "provenance_path": "tasks/b957ee230d748ac87a9bf7d1/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "f360215571c20caa64e358d00a2c49e7e756c9e7", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "a5c937624e4fa89bc47d15aeb5b89d3f414eca98", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d", + "task_sha256": "1eb12d12f3e7eb6f57afb10598ec9cc623ef9ebcc166407880a70d9280dc4da4", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "edcdafeda5783ab66a892128de00beda6139cd566848b6f3a70ea31c4931143d", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..953d946ba0c37042296bedb9bb1ea64a497b8a10 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"encoding.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCikKCmNvbnN0ICgKCXRpbWVzdGFtcFNpemVJbkJ5dGVzID0gOCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgdGltZXN0YW1wCgloYXNoU2l6ZUluQnl0ZXMgICAgICA9IDggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLy8gTnVtYmVyIG9mIGJ5dGVzIHVzZWQgZm9yIGhhc2gKCWtleVNpemVJbkJ5dGVzICAgICAgID0gMiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3Igc2l6ZSBvZiBlbnRyeSBrZXkKCWhlYWRlcnNTaXplSW5CeXRlcyAgID0gdGltZXN0YW1wU2l6ZUluQnl0ZXMgKyBoYXNoU2l6ZUluQnl0ZXMgKyBrZXlTaXplSW5CeXRlcyAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgYWxsIGhlYWRlcnMKKQoKZnVuYyB3cmFwRW50cnkodGltZXN0YW1wIHVpbnQ2NCwgaGFzaCB1aW50NjQsIGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSwgYnVmZmVyICpbXWJ5dGUpIFtdYnl0ZSB7CglrZXlMZW5ndGggOj0gbGVuKGtleSkKCWJsb2JMZW5ndGggOj0gbGVuKGVudHJ5KSArIGhlYWRlcnNTaXplSW5CeXRlcyArIGtleUxlbmd0aAoKCWlmIGJsb2JMZW5ndGggPiBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCWJsb2IgOj0gKmJ1ZmZlcgoKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2IsIHRpbWVzdGFtcCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgaGFzaCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDE2KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0sIHVpbnQxNihrZXlMZW5ndGgpKQoJY29weShibG9iW2hlYWRlcnNTaXplSW5CeXRlczpdLCBrZXkpCgljb3B5KGJsb2JbaGVhZGVyc1NpemVJbkJ5dGVzK2tleUxlbmd0aDpdLCBlbnRyeSkKCglyZXR1cm4gYmxvYls6YmxvYkxlbmd0aF0KfQoKZnVuYyBhcHBlbmRUb1dyYXBwZWRFbnRyeSh0aW1lc3RhbXAgdWludDY0LCB3cmFwcGVkRW50cnkgW11ieXRlLCBlbnRyeSBbXWJ5dGUsIGJ1ZmZlciAqW11ieXRlKSBbXWJ5dGUgewoJYmxvYkxlbmd0aCA6PSBsZW4od3JhcHBlZEVudHJ5KSArIGxlbihlbnRyeSkKCWlmIGJsb2JMZW5ndGggPiBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCglibG9iIDo9ICpidWZmZXIKCgliaW5hcnkuTGl0dGxlRW5kaWFuLlB1dFVpbnQ2NChibG9iLCB0aW1lc3RhbXApCgljb3B5KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgd3JhcHBlZEVudHJ5W3RpbWVzdGFtcFNpemVJbkJ5dGVzOl0pCgljb3B5KGJsb2JbbGVuKHdyYXBwZWRFbnRyeSk6XSwgZW50cnkpCgoJcmV0dXJuIGJsb2JbOmJsb2JMZW5ndGhdCn0KCmZ1bmMgcmVhZEVudHJ5KGRhdGEgW11ieXRlKSBbXWJ5dGUgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbihkYXRhKS1pbnQoaGVhZGVyc1NpemVJbkJ5dGVzK2xlbmd0aCkpCgljb3B5KGRzdCwgZGF0YVtoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoOl0pCgoJcmV0dXJuIGRzdAp9CgpmdW5jIHJlYWRUaW1lc3RhbXBGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YSkKfQoKZnVuYyByZWFkS2V5RnJvbUVudHJ5KGRhdGEgW11ieXRlKSBzdHJpbmcgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbmd0aCkKCWNvcHkoZHN0LCBkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkc3QpCn0KCmZ1bmMgY29tcGFyZUtleUZyb21FbnRyeShkYXRhIFtdYnl0ZSwga2V5IHN0cmluZykgYm9vbCB7CglsZW5ndGggOj0gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50MTYoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlcytoYXNoU2l6ZUluQnl0ZXM6XSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkgPT0ga2V5Cn0KCmZ1bmMgcmVhZEhhc2hGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdKQp9CgpmdW5jIHJlc2V0SGFzaEZyb21FbnRyeShkYXRhIFtdYnl0ZSkgewoJYmluYXJ5LkxpdHRsZUVuZGlhbi5QdXRVaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdLCAwKQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a6ab85ec4c06c9b2f5161ae6135e15702a044f9d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:0972f5e86fa971adeb970d03107cdb8d43ab63367c76a958a0850a816b6db43b" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..5b218888c4462e72a898a9649ab871851f463718 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/manifest.json @@ -0,0 +1,256 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/partial-repair.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ce008d6c55c19ed2888baff28fd01bec3c3249c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"encoding.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCikKCmNvbnN0ICgKCXRpbWVzdGFtcFNpemVJbkJ5dGVzID0gOCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgdGltZXN0YW1wCgloYXNoU2l6ZUluQnl0ZXMgICAgICA9IDggICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgLy8gTnVtYmVyIG9mIGJ5dGVzIHVzZWQgZm9yIGhhc2gKCWtleVNpemVJbkJ5dGVzICAgICAgID0gMiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3Igc2l6ZSBvZiBlbnRyeSBrZXkKCWhlYWRlcnNTaXplSW5CeXRlcyAgID0gdGltZXN0YW1wU2l6ZUluQnl0ZXMgKyBoYXNoU2l6ZUluQnl0ZXMgKyBrZXlTaXplSW5CeXRlcyAvLyBOdW1iZXIgb2YgYnl0ZXMgdXNlZCBmb3IgYWxsIGhlYWRlcnMKKQoKZnVuYyB3cmFwRW50cnkodGltZXN0YW1wIHVpbnQ2NCwgaGFzaCB1aW50NjQsIGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSwgYnVmZmVyICpbXWJ5dGUpIFtdYnl0ZSB7CglrZXlMZW5ndGggOj0gbGVuKGtleSkKCWJsb2JMZW5ndGggOj0gbGVuKGVudHJ5KSArIGhlYWRlcnNTaXplSW5CeXRlcyArIGtleUxlbmd0aAoKCWlmIGxlbigqYnVmZmVyKSA+IGJsb2JMZW5ndGggewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCWJsb2IgOj0gKmJ1ZmZlcgoKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2IsIHRpbWVzdGFtcCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDY0KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgaGFzaCkKCWJpbmFyeS5MaXR0bGVFbmRpYW4uUHV0VWludDE2KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0sIHVpbnQxNihrZXlMZW5ndGgpKQoJY29weShibG9iW2hlYWRlcnNTaXplSW5CeXRlczpdLCBrZXkpCgljb3B5KGJsb2JbaGVhZGVyc1NpemVJbkJ5dGVzK2tleUxlbmd0aDpdLCBlbnRyeSkKCglyZXR1cm4gYmxvYls6YmxvYkxlbmd0aF0KfQoKZnVuYyBhcHBlbmRUb1dyYXBwZWRFbnRyeSh0aW1lc3RhbXAgdWludDY0LCB3cmFwcGVkRW50cnkgW11ieXRlLCBlbnRyeSBbXWJ5dGUsIGJ1ZmZlciAqW11ieXRlKSBbXWJ5dGUgewoJYmxvYkxlbmd0aCA6PSBsZW4od3JhcHBlZEVudHJ5KSArIGxlbihlbnRyeSkKCWlmIGJsb2JMZW5ndGggPiBsZW4oKmJ1ZmZlcikgewoJCSpidWZmZXIgPSBtYWtlKFtdYnl0ZSwgYmxvYkxlbmd0aCkKCX0KCglibG9iIDo9ICpidWZmZXIKCgliaW5hcnkuTGl0dGxlRW5kaWFuLlB1dFVpbnQ2NChibG9iLCB0aW1lc3RhbXApCgljb3B5KGJsb2JbdGltZXN0YW1wU2l6ZUluQnl0ZXM6XSwgd3JhcHBlZEVudHJ5W3RpbWVzdGFtcFNpemVJbkJ5dGVzOl0pCgljb3B5KGJsb2JbbGVuKHdyYXBwZWRFbnRyeSk6XSwgZW50cnkpCgoJcmV0dXJuIGJsb2JbOmJsb2JMZW5ndGhdCn0KCmZ1bmMgcmVhZEVudHJ5KGRhdGEgW11ieXRlKSBbXWJ5dGUgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbihkYXRhKS1pbnQoaGVhZGVyc1NpemVJbkJ5dGVzK2xlbmd0aCkpCgljb3B5KGRzdCwgZGF0YVtoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoOl0pCgoJcmV0dXJuIGRzdAp9CgpmdW5jIHJlYWRUaW1lc3RhbXBGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YSkKfQoKZnVuYyByZWFkS2V5RnJvbUVudHJ5KGRhdGEgW11ieXRlKSBzdHJpbmcgewoJbGVuZ3RoIDo9IGJpbmFyeS5MaXR0bGVFbmRpYW4uVWludDE2KGRhdGFbdGltZXN0YW1wU2l6ZUluQnl0ZXMraGFzaFNpemVJbkJ5dGVzOl0pCgoJLy8gY29weSBvbiByZWFkCglkc3QgOj0gbWFrZShbXWJ5dGUsIGxlbmd0aCkKCWNvcHkoZHN0LCBkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkc3QpCn0KCmZ1bmMgY29tcGFyZUtleUZyb21FbnRyeShkYXRhIFtdYnl0ZSwga2V5IHN0cmluZykgYm9vbCB7CglsZW5ndGggOj0gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50MTYoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlcytoYXNoU2l6ZUluQnl0ZXM6XSkKCglyZXR1cm4gYnl0ZXNUb1N0cmluZyhkYXRhW2hlYWRlcnNTaXplSW5CeXRlczpoZWFkZXJzU2l6ZUluQnl0ZXMrbGVuZ3RoXSkgPT0ga2V5Cn0KCmZ1bmMgcmVhZEhhc2hGcm9tRW50cnkoZGF0YSBbXWJ5dGUpIHVpbnQ2NCB7CglyZXR1cm4gYmluYXJ5LkxpdHRsZUVuZGlhbi5VaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdKQp9CgpmdW5jIHJlc2V0SGFzaEZyb21FbnRyeShkYXRhIFtdYnl0ZSkgewoJYmluYXJ5LkxpdHRsZUVuZGlhbi5QdXRVaW50NjQoZGF0YVt0aW1lc3RhbXBTaXplSW5CeXRlczpdLCAwKQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..5851c153eb6a3bff2825b718c92f767f8c16258d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_op_swap__oks6kc3d/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "ab03f6b48b2ee6f0704dd130e195a36915db06fbd2318462032ad50bc7a49317", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..2aa21b779cdfef0b1a07aa0f4fb45bf809d55324 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + + } + } + + + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4420c2a7cf65b0c09d647e1b4defc17029de731e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/instruction.md @@ -0,0 +1,35 @@ +BytesQueue memory allocation broken after recent changes + +#### Description + +The BytesQueue is experiencing slice bounds out of range panics when trying to access queue data after memory allocation. This appears to be related to the allocateAdditionalMemory function not properly updating internal state variables. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + config := bigcache.DefaultConfig(10 * time.Minute) + config.Verbose = true + + cache, _ := bigcache.NewBigCache(config) + + // This should trigger memory allocation and cause a panic + cache.Set("test", make([]byte, 200)) + cache.Set("test", make([]byte, 300)) // Bigger entry to force reallocation +} +``` + +The issue manifests as: +``` +panic: runtime error: slice bounds out of range [:143] with capacity 40 +``` + +This happens when the queue tries to peek at data after allocating additional memory, suggesting that the internal pointers or capacity tracking is incorrect after reallocation. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..d3977c6ec22fe0d22e8b068b6a80afcf6f5ef28d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/provenance.json @@ -0,0 +1,372 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "original-bug": "task-specific unchanged semantic bug", + "partial-repair": "strict partial repair candidate with independently unproven wrongness", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "acceptance_disposition": "needs_semantic_review; may be a legitimate alternative; do not cherry-pick another canary from measured rewards", + "candidate_file_inventory": { + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "af658c37d718ad11a54c64de369726c64f9ac3ae5cf37dc3be45e25c67e8792e", + "size": 6835 + } + }, + "expected_wrongness": "unproven until independent semantic review", + "original_patch_hunks": 2, + "original_patch_sha256": "4381d674b544c457936d391aa363b139a224ea72005441f3c3a7d07d69add1f9", + "retained_mutation_file": "queue/bytes_queue.go", + "retained_mutation_hunk_sha256": "e4facbd0150d71d515161f851b6f78452cc118924174c1203d161e8158708855" + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "61ed7215cef1308669fbf84c287a5558697a8b1cd03463cf278fcc363985ffdb", + "size": 6799 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "d19e554be4602d9e67edcb34fde9a10a72363b4fdab24a04069dcb9340f4ff2f", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": null, + "source_proof_sha256": "db0e195036550a323eb163db67f3b5516989a01a0d7c05d67937ad0d408508b3", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "35807b0abe46dfbab676b11bdda5f1f47c6f4f4763804dffc25e8946d423e5dc", + "is_fork": true, + "learner_path": "tasks/9e405581a4f9932bb0e57d58/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/b85793d785d10fa1066bf18031f3c7def537d692/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "4381d674b544c457936d391aa363b139a224ea72005441f3c3a7d07d69add1f9", + "provenance_path": "tasks/9e405581a4f9932bb0e57d58/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "b85793d785d10fa1066bf18031f3c7def537d692", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "efe3ac74bc95b2e2b54f4d7c4f652f397b540528", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4", + "task_sha256": "68c35e7a989eec02db67642b0f313b2f572c2e7a888a04eb36ddef1732dcf684", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "e9a2d7561593a29ee7af26ef00eebdb407c9f99957cefcb965719bc6cc152b6f", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2e4f032645f70e7b7e425953ed99476d657d7ce3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"queue/bytes_queue.go": {"data": "cGFja2FnZSBxdWV1ZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCgkibG9nIgoJInRpbWUiCikKCmNvbnN0ICgKCS8vIE51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgMCBpbiB1dmFyaW50IGZvcm1hdAoJbWluaW11bUhlYWRlclNpemUgPSAxNyAvLyAxIGJ5dGUgYmxvYnNpemUgKyB0aW1lc3RhbXBTaXplSW5CeXRlcyArIGhhc2hTaXplSW5CeXRlcwoJLy8gQnl0ZXMgYmVmb3JlIGxlZnQgbWFyZ2luIGFyZSBub3QgdXNlZC4gWmVybyBpbmRleCBtZWFucyBlbGVtZW50IGRvZXMgbm90IGV4aXN0IGluIHF1ZXVlLCB1c2VmdWwgd2hpbGUgcmVhZGluZyBzbGljZSBmcm9tIGluZGV4CglsZWZ0TWFyZ2luSW5kZXggPSAxCikKCnZhciAoCgllcnJFbXB0eVF1ZXVlICAgICAgID0gJnF1ZXVlRXJyb3J7IkVtcHR5IHF1ZXVlIn0KCWVyckludmFsaWRJbmRleCAgICAgPSAmcXVldWVFcnJvcnsiSW5kZXggbXVzdCBiZSBncmVhdGVyIHRoYW4gemVyby4gSW52YWxpZCBpbmRleC4ifQoJZXJySW5kZXhPdXRPZkJvdW5kcyA9ICZxdWV1ZUVycm9yeyJJbmRleCBvdXQgb2YgcmFuZ2UifQopCgovLyBCeXRlc1F1ZXVlIGlzIGEgbm9uLXRocmVhZCBzYWZlIHF1ZXVlIHR5cGUgb2YgZmlmbyBiYXNlZCBvbiBieXRlcyBhcnJheS4KLy8gRm9yIGV2ZXJ5IHB1c2ggb3BlcmF0aW9uIGluZGV4IG9mIGVudHJ5IGlzIHJldHVybmVkLiBJdCBjYW4gYmUgdXNlZCB0byByZWFkIHRoZSBlbnRyeSBsYXRlcgp0eXBlIEJ5dGVzUXVldWUgc3RydWN0IHsKCWZ1bGwgICAgICAgICBib29sCglhcnJheSAgICAgICAgW11ieXRlCgljYXBhY2l0eSAgICAgaW50CgltYXhDYXBhY2l0eSAgaW50CgloZWFkICAgICAgICAgaW50Cgl0YWlsICAgICAgICAgaW50Cgljb3VudCAgICAgICAgaW50CglyaWdodE1hcmdpbiAgaW50CgloZWFkZXJCdWZmZXIgW11ieXRlCgl2ZXJib3NlICAgICAgYm9vbAp9Cgp0eXBlIHF1ZXVlRXJyb3Igc3RydWN0IHsKCW1lc3NhZ2Ugc3RyaW5nCn0KCi8vIGdldE5lZWRlZFNpemUgcmV0dXJucyB0aGUgbnVtYmVyIG9mIGJ5dGVzIGFuIGVudHJ5IG9mIGxlbmd0aCBuZWVkIGluIHRoZSBxdWV1ZQpmdW5jIGdldE5lZWRlZFNpemUobGVuZ3RoIGludCkgaW50IHsKCXZhciBoZWFkZXIgaW50Cglzd2l0Y2ggewoJY2FzZSBsZW5ndGggPCAxMjc6IC8vIDE8PDctMQoJCWhlYWRlciA9IDEKCWNhc2UgbGVuZ3RoIDwgMTYzODI6IC8vIDE8PDE0LTIKCQloZWFkZXIgPSAyCgljYXNlIGxlbmd0aCA8IDIwOTcxNDk6IC8vIDE8PDIxIC0zCgkJaGVhZGVyID0gMwoJY2FzZSBsZW5ndGggPCAyNjg0MzU0NTI6IC8vIDE8PDI4IC00CgkJaGVhZGVyID0gNAoJZGVmYXVsdDoKCQloZWFkZXIgPSA1Cgl9CgoJcmV0dXJuIGxlbmd0aCArIGhlYWRlcgp9CgovLyBOZXdCeXRlc1F1ZXVlIGluaXRpYWxpemUgbmV3IGJ5dGVzIHF1ZXVlLgovLyBjYXBhY2l0eSBpcyB1c2VkIGluIGJ5dGVzIGFycmF5IGFsbG9jYXRpb24KLy8gV2hlbiB2ZXJib3NlIGZsYWcgaXMgc2V0IHRoZW4gaW5mb3JtYXRpb24gYWJvdXQgbWVtb3J5IGFsbG9jYXRpb24gYXJlIHByaW50ZWQKZnVuYyBOZXdCeXRlc1F1ZXVlKGNhcGFjaXR5IGludCwgbWF4Q2FwYWNpdHkgaW50LCB2ZXJib3NlIGJvb2wpICpCeXRlc1F1ZXVlIHsKCXJldHVybiAmQnl0ZXNRdWV1ZXsKCQlhcnJheTogICAgICAgIG1ha2UoW11ieXRlLCBjYXBhY2l0eSksCgkJY2FwYWNpdHk6ICAgICBjYXBhY2l0eSwKCQltYXhDYXBhY2l0eTogIG1heENhcGFjaXR5LAoJCWhlYWRlckJ1ZmZlcjogbWFrZShbXWJ5dGUsIGJpbmFyeS5NYXhWYXJpbnRMZW4zMiksCgkJdGFpbDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJaGVhZDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJcmlnaHRNYXJnaW46ICBsZWZ0TWFyZ2luSW5kZXgsCgkJdmVyYm9zZTogICAgICB2ZXJib3NlLAoJfQp9CgovLyBSZXNldCByZW1vdmVzIGFsbCBlbnRyaWVzIGZyb20gcXVldWUKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgUmVzZXQoKSB7CgkvLyBKdXN0IHJlc2V0IGluZGV4ZXMKCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJcS5oZWFkID0gbGVmdE1hcmdpbkluZGV4CglxLnJpZ2h0TWFyZ2luID0gbGVmdE1hcmdpbkluZGV4CglxLmNvdW50ID0gMAoJcS5mdWxsID0gZmFsc2UKfQoKLy8gUHVzaCBjb3BpZXMgZW50cnkgYXQgdGhlIGVuZCBvZiBxdWV1ZSBhbmQgbW92ZXMgdGFpbCBwb2ludGVyLiBBbGxvY2F0ZXMgbW9yZSBzcGFjZSBpZiBuZWVkZWQuCi8vIFJldHVybnMgaW5kZXggZm9yIHB1c2hlZCBkYXRhIG9yIGVycm9yIGlmIG1heGltdW0gc2l6ZSBxdWV1ZSBsaW1pdCBpcyByZWFjaGVkLgpmdW5jIChxICpCeXRlc1F1ZXVlKSBQdXNoKGRhdGEgW11ieXRlKSAoaW50LCBlcnJvcikgewoJbmVlZGVkU2l6ZSA6PSBnZXROZWVkZWRTaXplKGxlbihkYXRhKSkKCglpZiAhcS5jYW5JbnNlcnRBZnRlclRhaWwobmVlZGVkU2l6ZSkgewoJCWlmIHEuY2FuSW5zZXJ0QmVmb3JlSGVhZChuZWVkZWRTaXplKSB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0gZWxzZSBpZiBxLmNhcGFjaXR5K25lZWRlZFNpemUgPj0gcS5tYXhDYXBhY2l0eSAmJiBxLm1heENhcGFjaXR5ID4gMCB7CgkJCXJldHVybiAtMSwgJnF1ZXVlRXJyb3J7IkZ1bGwgcXVldWUuIE1heGltdW0gc2l6ZSBsaW1pdCByZWFjaGVkLiJ9CgkJfSBlbHNlIHsKCQkJcS5hbGxvY2F0ZUFkZGl0aW9uYWxNZW1vcnkobmVlZGVkU2l6ZSkKCQl9Cgl9CgoJaW5kZXggOj0gcS50YWlsCgoJcS5wdXNoKGRhdGEsIG5lZWRlZFNpemUpCgoJcmV0dXJuIGluZGV4LCBuaWwKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgYWxsb2NhdGVBZGRpdGlvbmFsTWVtb3J5KG1pbmltdW0gaW50KSB7CglzdGFydCA6PSB0aW1lLk5vdygpCglpZiBxLmNhcGFjaXR5IDwgbWluaW11bSB7CgkJcS5jYXBhY2l0eSArPSBtaW5pbXVtCgl9CglxLmNhcGFjaXR5ID0gcS5jYXBhY2l0eSAqIDIKCWlmIHEuY2FwYWNpdHkgPiBxLm1heENhcGFjaXR5ICYmIHEubWF4Q2FwYWNpdHkgPiAwIHsKCQlxLmNhcGFjaXR5ID0gcS5tYXhDYXBhY2l0eQoJfQoKCW9sZEFycmF5IDo9IHEuYXJyYXkKCXEuYXJyYXkgPSBtYWtlKFtdYnl0ZSwgcS5jYXBhY2l0eSkKCglpZiBsZWZ0TWFyZ2luSW5kZXggIT0gcS5yaWdodE1hcmdpbiB7CgkJY29weShxLmFycmF5LCBvbGRBcnJheVs6cS5yaWdodE1hcmdpbl0pCgoJCWlmIHEudGFpbCA8PSBxLmhlYWQgewoJCQlpZiBxLnRhaWwgIT0gcS5oZWFkIHsKCQkJCS8vIGNyZWF0ZWQgc2xpY2UgaXMgc2xpZ2h0bHkgbGFyZ2VyIHRoYW4gbmVlZCBidXQgdGhpcyBpcyBmaW5lIGFmdGVyIG9ubHkgdGhlIG5lZWRlZCBieXRlcyBhcmUgY29waWVkCgkJCQlxLnB1c2gobWFrZShbXWJ5dGUsIHEuaGVhZC1xLnRhaWwpLCBxLmhlYWQtcS50YWlsKQoJCQl9CgoJCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQkJcS50YWlsID0gcS5yaWdodE1hcmdpbgoJCX0KCX0KCglxLmZ1bGwgPSBmYWxzZQoKCWlmIHEudmVyYm9zZSB7CgkJbG9nLlByaW50ZigiQWxsb2NhdGVkIG5ldyBxdWV1ZSBpbiAlczsgQ2FwYWNpdHk6ICVkIFxuIiwgdGltZS5TaW5jZShzdGFydCksIHEuY2FwYWNpdHkpCgl9Cn0KCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIHB1c2goZGF0YSBbXWJ5dGUsIGxlbiBpbnQpIHsKCWhlYWRlckVudHJ5U2l6ZSA6PSBiaW5hcnkuUHV0VXZhcmludChxLmhlYWRlckJ1ZmZlciwgdWludDY0KGxlbikpCglxLmNvcHkocS5oZWFkZXJCdWZmZXIsIGhlYWRlckVudHJ5U2l6ZSkKCglxLmNvcHkoZGF0YSwgbGVuLWhlYWRlckVudHJ5U2l6ZSkKCglpZiBxLnRhaWwgPiBxLmhlYWQgewoJCXEucmlnaHRNYXJnaW4gPSBxLnRhaWwKCX0KCWlmIHEudGFpbCA9PSBxLmhlYWQgewoJCXEuZnVsbCA9IHRydWUKCX0KCglxLmNvdW50KysKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgY29weShkYXRhIFtdYnl0ZSwgbGVuIGludCkgewoJcS50YWlsICs9IGNvcHkocS5hcnJheVtxLnRhaWw6XSwgZGF0YVs6bGVuXSkKfQoKLy8gUG9wIHJlYWRzIHRoZSBvbGRlc3QgZW50cnkgZnJvbSBxdWV1ZSBhbmQgbW92ZXMgaGVhZCBwb2ludGVyIHRvIHRoZSBuZXh0IG9uZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBQb3AoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgYmxvY2tTaXplLCBlcnIgOj0gcS5wZWVrKHEuaGVhZCkKCWlmIGVyciAhPSBuaWwgewoJCXJldHVybiBuaWwsIGVycgoJfQoKCXEuaGVhZCArPSBibG9ja1NpemUKCXEuY291bnQtLQoKCWlmIHEuaGVhZCA9PSBxLnJpZ2h0TWFyZ2luIHsKCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQlpZiBxLnRhaWwgPT0gcS5yaWdodE1hcmdpbiB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0KCQlxLnJpZ2h0TWFyZ2luID0gcS50YWlsCgl9CgoJcS5mdWxsID0gZmFsc2UKCglyZXR1cm4gZGF0YSwgbmlsCn0KCi8vIFBlZWsgcmVhZHMgdGhlIG9sZGVzdCBlbnRyeSBmcm9tIGxpc3Qgd2l0aG91dCBtb3ZpbmcgaGVhZCBwb2ludGVyCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIFBlZWsoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgXywgZXJyIDo9IHEucGVlayhxLmhlYWQpCglyZXR1cm4gZGF0YSwgZXJyCn0KCi8vIEdldCByZWFkcyBlbnRyeSBmcm9tIGluZGV4CmZ1bmMgKHEgKkJ5dGVzUXVldWUpIEdldChpbmRleCBpbnQpIChbXWJ5dGUsIGVycm9yKSB7CglkYXRhLCBfLCBlcnIgOj0gcS5wZWVrKGluZGV4KQoJcmV0dXJuIGRhdGEsIGVycgp9CgovLyBDaGVja0dldCBjaGVja3MgaWYgYW4gZW50cnkgY2FuIGJlIHJlYWQgZnJvbSBpbmRleApmdW5jIChxICpCeXRlc1F1ZXVlKSBDaGVja0dldChpbmRleCBpbnQpIGVycm9yIHsKCXJldHVybiBxLnBlZWtDaGVja0VycihpbmRleCkKfQoKLy8gQ2FwYWNpdHkgcmV0dXJucyBudW1iZXIgb2YgYWxsb2NhdGVkIGJ5dGVzIGZvciBxdWV1ZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBDYXBhY2l0eSgpIGludCB7CglyZXR1cm4gcS5jYXBhY2l0eQp9CgovLyBMZW4gcmV0dXJucyBudW1iZXIgb2YgZW50cmllcyBrZXB0IGluIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIExlbigpIGludCB7CglyZXR1cm4gcS5jb3VudAp9CgovLyBFcnJvciByZXR1cm5zIGVycm9yIG1lc3NhZ2UKZnVuYyAoZSAqcXVldWVFcnJvcikgRXJyb3IoKSBzdHJpbmcgewoJcmV0dXJuIGUubWVzc2FnZQp9CgovLyBwZWVrQ2hlY2tFcnIgaXMgaWRlbnRpY2FsIHRvIHBlZWssIGJ1dCBkb2VzIG5vdCBhY3R1YWxseSByZXR1cm4gYW55IGRhdGEKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgcGVla0NoZWNrRXJyKGluZGV4IGludCkgZXJyb3IgewoKCWlmIHEuY291bnQgPT0gMCB7CgkJcmV0dXJuIGVyckVtcHR5UXVldWUKCX0KCglpZiBpbmRleCA8PSAwIHsKCQlyZXR1cm4gZXJySW52YWxpZEluZGV4Cgl9CgoJaWYgaW5kZXggPj0gbGVuKHEuYXJyYXkpIHsKCQlyZXR1cm4gZXJySW5kZXhPdXRPZkJvdW5kcwoJfQoJcmV0dXJuIG5pbAp9CgovLyBwZWVrIHJldHVybnMgdGhlIGRhdGEgZnJvbSBpbmRleCBhbmQgdGhlIG51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgdGhlIGxlbmd0aCBvZiB0aGUgZGF0YSBpbiB1dmFyaW50IGZvcm1hdApmdW5jIChxICpCeXRlc1F1ZXVlKSBwZWVrKGluZGV4IGludCkgKFtdYnl0ZSwgaW50LCBlcnJvcikgewoJZXJyIDo9IHEucGVla0NoZWNrRXJyKGluZGV4KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgMCwgZXJyCgl9CgoJYmxvY2tTaXplLCBuIDo9IGJpbmFyeS5VdmFyaW50KHEuYXJyYXlbaW5kZXg6XSkKCXJldHVybiBxLmFycmF5W2luZGV4K24gOiBpbmRleCtpbnQoYmxvY2tTaXplKV0sIGludChibG9ja1NpemUpLCBuaWwKfQoKLy8gY2FuSW5zZXJ0QWZ0ZXJUYWlsIHJldHVybnMgdHJ1ZSBpZiBpdCdzIHBvc3NpYmxlIHRvIGluc2VydCBhbiBlbnRyeSBvZiBzaXplIG9mIG5lZWQgYWZ0ZXIgdGhlIHRhaWwgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEFmdGVyVGFpbChuZWVkIGludCkgYm9vbCB7CglpZiBxLmZ1bGwgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgcS50YWlsID49IHEuaGVhZCB7CgkJcmV0dXJuIHEuY2FwYWNpdHktcS50YWlsID49IG5lZWQKCX0KCS8vIDEuIHRoZXJlIGlzIGV4YWN0bHkgbmVlZCBieXRlcyBiZXR3ZWVuIGhlYWQgYW5kIHRhaWwsIHNvIHdlIGRvIG5vdCBuZWVkCgkvLyB0byByZXNlcnZlIGV4dHJhIHNwYWNlIGZvciBhIHBvdGVudGlhbCBlbXB0eSBlbnRyeSB3aGVuIHJlYWxsb2MgdGhpcyBxdWV1ZQoJLy8gMi4gc3RpbGwgaGF2ZSB1bnVzZWQgc3BhY2UgYmV0d2VlbiB0YWlsIGFuZCBoZWFkLCB0aGVuIHdlIG11c3QgcmVzZXJ2ZQoJLy8gYXQgbGVhc3QgaGVhZGVyRW50cnlTaXplIGJ5dGVzIHNvIHdlIGNhbiBwdXQgYW4gZW1wdHkgZW50cnkKCXJldHVybiBxLmhlYWQtcS50YWlsID09IG5lZWQgfHwgcS5oZWFkLXEudGFpbCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCn0KCi8vIGNhbkluc2VydEJlZm9yZUhlYWQgcmV0dXJucyB0cnVlIGlmIGl0J3MgcG9zc2libGUgdG8gaW5zZXJ0IGFuIGVudHJ5IG9mIHNpemUgb2YgbmVlZCBiZWZvcmUgdGhlIGhlYWQgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEJlZm9yZUhlYWQobmVlZCBpbnQpIGJvb2wgewoJaWYgcS5mdWxsIHsKCQlyZXR1cm4gZmFsc2UKCX0KCWlmIHEudGFpbCA+PSBxLmhlYWQgewoJCXJldHVybiBxLmhlYWQtbGVmdE1hcmdpbkluZGV4ID09IG5lZWQgfHwgcS5oZWFkLWxlZnRNYXJnaW5JbmRleCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCgl9CglyZXR1cm4gcS5oZWFkLXEudGFpbCA9PSBuZWVkIHx8IHEuaGVhZC1xLnRhaWwgPj0gbmVlZCttaW5pbXVtSGVhZGVyU2l6ZQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..355aa0a62cf13d63654b442e45834adfce3983e2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:d8d9102d74cd7a36a212f59248d0c9884e43cd0a894e16164727db764acefb6c" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..990fbf9b126369b3328e0bf89f737e1851d9b6e3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/manifest.json @@ -0,0 +1,206 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/partial-repair.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/partial-repair.sh new file mode 100644 index 0000000000000000000000000000000000000000..5dd5d244f747e7262245f898bfc7e0c9ab37da89 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/partial-repair.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"queue/bytes_queue.go": {"data": "cGFja2FnZSBxdWV1ZQoKaW1wb3J0ICgKCSJlbmNvZGluZy9iaW5hcnkiCgkibG9nIgoJInRpbWUiCikKCmNvbnN0ICgKCS8vIE51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgMCBpbiB1dmFyaW50IGZvcm1hdAoJbWluaW11bUhlYWRlclNpemUgPSAxNyAvLyAxIGJ5dGUgYmxvYnNpemUgKyB0aW1lc3RhbXBTaXplSW5CeXRlcyArIGhhc2hTaXplSW5CeXRlcwoJLy8gQnl0ZXMgYmVmb3JlIGxlZnQgbWFyZ2luIGFyZSBub3QgdXNlZC4gWmVybyBpbmRleCBtZWFucyBlbGVtZW50IGRvZXMgbm90IGV4aXN0IGluIHF1ZXVlLCB1c2VmdWwgd2hpbGUgcmVhZGluZyBzbGljZSBmcm9tIGluZGV4CglsZWZ0TWFyZ2luSW5kZXggPSAxCikKCnZhciAoCgllcnJFbXB0eVF1ZXVlICAgICAgID0gJnF1ZXVlRXJyb3J7IkVtcHR5IHF1ZXVlIn0KCWVyckludmFsaWRJbmRleCAgICAgPSAmcXVldWVFcnJvcnsiSW5kZXggbXVzdCBiZSBncmVhdGVyIHRoYW4gemVyby4gSW52YWxpZCBpbmRleC4ifQoJZXJySW5kZXhPdXRPZkJvdW5kcyA9ICZxdWV1ZUVycm9yeyJJbmRleCBvdXQgb2YgcmFuZ2UifQopCgovLyBCeXRlc1F1ZXVlIGlzIGEgbm9uLXRocmVhZCBzYWZlIHF1ZXVlIHR5cGUgb2YgZmlmbyBiYXNlZCBvbiBieXRlcyBhcnJheS4KLy8gRm9yIGV2ZXJ5IHB1c2ggb3BlcmF0aW9uIGluZGV4IG9mIGVudHJ5IGlzIHJldHVybmVkLiBJdCBjYW4gYmUgdXNlZCB0byByZWFkIHRoZSBlbnRyeSBsYXRlcgp0eXBlIEJ5dGVzUXVldWUgc3RydWN0IHsKCWZ1bGwgICAgICAgICBib29sCglhcnJheSAgICAgICAgW11ieXRlCgljYXBhY2l0eSAgICAgaW50CgltYXhDYXBhY2l0eSAgaW50CgloZWFkICAgICAgICAgaW50Cgl0YWlsICAgICAgICAgaW50Cgljb3VudCAgICAgICAgaW50CglyaWdodE1hcmdpbiAgaW50CgloZWFkZXJCdWZmZXIgW11ieXRlCgl2ZXJib3NlICAgICAgYm9vbAp9Cgp0eXBlIHF1ZXVlRXJyb3Igc3RydWN0IHsKCW1lc3NhZ2Ugc3RyaW5nCn0KCi8vIGdldE5lZWRlZFNpemUgcmV0dXJucyB0aGUgbnVtYmVyIG9mIGJ5dGVzIGFuIGVudHJ5IG9mIGxlbmd0aCBuZWVkIGluIHRoZSBxdWV1ZQpmdW5jIGdldE5lZWRlZFNpemUobGVuZ3RoIGludCkgaW50IHsKCXZhciBoZWFkZXIgaW50Cglzd2l0Y2ggewoJY2FzZSBsZW5ndGggPCAxMjc6IC8vIDE8PDctMQoJCWhlYWRlciA9IDEKCWNhc2UgbGVuZ3RoIDwgMTYzODI6IC8vIDE8PDE0LTIKCQloZWFkZXIgPSAyCgljYXNlIGxlbmd0aCA8IDIwOTcxNDk6IC8vIDE8PDIxIC0zCgkJaGVhZGVyID0gMwoJY2FzZSBsZW5ndGggPCAyNjg0MzU0NTI6IC8vIDE8PDI4IC00CgkJaGVhZGVyID0gNAoJZGVmYXVsdDoKCQloZWFkZXIgPSA1Cgl9CgoJcmV0dXJuIGxlbmd0aCArIGhlYWRlcgp9CgovLyBOZXdCeXRlc1F1ZXVlIGluaXRpYWxpemUgbmV3IGJ5dGVzIHF1ZXVlLgovLyBjYXBhY2l0eSBpcyB1c2VkIGluIGJ5dGVzIGFycmF5IGFsbG9jYXRpb24KLy8gV2hlbiB2ZXJib3NlIGZsYWcgaXMgc2V0IHRoZW4gaW5mb3JtYXRpb24gYWJvdXQgbWVtb3J5IGFsbG9jYXRpb24gYXJlIHByaW50ZWQKZnVuYyBOZXdCeXRlc1F1ZXVlKGNhcGFjaXR5IGludCwgbWF4Q2FwYWNpdHkgaW50LCB2ZXJib3NlIGJvb2wpICpCeXRlc1F1ZXVlIHsKCXJldHVybiAmQnl0ZXNRdWV1ZXsKCQlhcnJheTogICAgICAgIG1ha2UoW11ieXRlLCBjYXBhY2l0eSksCgkJY2FwYWNpdHk6ICAgICBjYXBhY2l0eSwKCQltYXhDYXBhY2l0eTogIG1heENhcGFjaXR5LAoJCWhlYWRlckJ1ZmZlcjogbWFrZShbXWJ5dGUsIGJpbmFyeS5NYXhWYXJpbnRMZW4zMiksCgkJdGFpbDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJaGVhZDogICAgICAgICBsZWZ0TWFyZ2luSW5kZXgsCgkJcmlnaHRNYXJnaW46ICBsZWZ0TWFyZ2luSW5kZXgsCgkJdmVyYm9zZTogICAgICB2ZXJib3NlLAoJfQp9CgovLyBSZXNldCByZW1vdmVzIGFsbCBlbnRyaWVzIGZyb20gcXVldWUKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgUmVzZXQoKSB7CgkvLyBKdXN0IHJlc2V0IGluZGV4ZXMKCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJcS5oZWFkID0gbGVmdE1hcmdpbkluZGV4CglxLnJpZ2h0TWFyZ2luID0gbGVmdE1hcmdpbkluZGV4CglxLmNvdW50ID0gMAoJcS5mdWxsID0gZmFsc2UKfQoKLy8gUHVzaCBjb3BpZXMgZW50cnkgYXQgdGhlIGVuZCBvZiBxdWV1ZSBhbmQgbW92ZXMgdGFpbCBwb2ludGVyLiBBbGxvY2F0ZXMgbW9yZSBzcGFjZSBpZiBuZWVkZWQuCi8vIFJldHVybnMgaW5kZXggZm9yIHB1c2hlZCBkYXRhIG9yIGVycm9yIGlmIG1heGltdW0gc2l6ZSBxdWV1ZSBsaW1pdCBpcyByZWFjaGVkLgpmdW5jIChxICpCeXRlc1F1ZXVlKSBQdXNoKGRhdGEgW11ieXRlKSAoaW50LCBlcnJvcikgewoJbmVlZGVkU2l6ZSA6PSBnZXROZWVkZWRTaXplKGxlbihkYXRhKSkKCglpZiAhcS5jYW5JbnNlcnRBZnRlclRhaWwobmVlZGVkU2l6ZSkgewoJCWlmIHEuY2FuSW5zZXJ0QmVmb3JlSGVhZChuZWVkZWRTaXplKSB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0gZWxzZSBpZiBxLmNhcGFjaXR5K25lZWRlZFNpemUgPj0gcS5tYXhDYXBhY2l0eSAmJiBxLm1heENhcGFjaXR5ID4gMCB7CgkJCXJldHVybiAtMSwgJnF1ZXVlRXJyb3J7IkZ1bGwgcXVldWUuIE1heGltdW0gc2l6ZSBsaW1pdCByZWFjaGVkLiJ9CgkJfSBlbHNlIHsKCQkJcS5hbGxvY2F0ZUFkZGl0aW9uYWxNZW1vcnkobmVlZGVkU2l6ZSkKCQl9Cgl9CgoJaW5kZXggOj0gcS50YWlsCgoJcS5wdXNoKGRhdGEsIG5lZWRlZFNpemUpCgoJcmV0dXJuIGluZGV4LCBuaWwKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgYWxsb2NhdGVBZGRpdGlvbmFsTWVtb3J5KG1pbmltdW0gaW50KSB7CglzdGFydCA6PSB0aW1lLk5vdygpCglpZiBxLmNhcGFjaXR5IDwgbWluaW11bSB7CgkJCgl9CglxLmNhcGFjaXR5ID0gcS5jYXBhY2l0eSAqIDIKCWlmIHEuY2FwYWNpdHkgPiBxLm1heENhcGFjaXR5ICYmIHEubWF4Q2FwYWNpdHkgPiAwIHsKCQlxLmNhcGFjaXR5ID0gcS5tYXhDYXBhY2l0eQoJfQoKCW9sZEFycmF5IDo9IHEuYXJyYXkKCXEuYXJyYXkgPSBtYWtlKFtdYnl0ZSwgcS5jYXBhY2l0eSkKCglpZiBsZWZ0TWFyZ2luSW5kZXggIT0gcS5yaWdodE1hcmdpbiB7CgkJY29weShxLmFycmF5LCBvbGRBcnJheVs6cS5yaWdodE1hcmdpbl0pCgoJCWlmIHEudGFpbCA8PSBxLmhlYWQgewoJCQlpZiBxLnRhaWwgIT0gcS5oZWFkIHsKCQkJCS8vIGNyZWF0ZWQgc2xpY2UgaXMgc2xpZ2h0bHkgbGFyZ2VyIHRoYW4gbmVlZCBidXQgdGhpcyBpcyBmaW5lIGFmdGVyIG9ubHkgdGhlIG5lZWRlZCBieXRlcyBhcmUgY29waWVkCgkJCQlxLnB1c2gobWFrZShbXWJ5dGUsIHEuaGVhZC1xLnRhaWwpLCBxLmhlYWQtcS50YWlsKQoJCQl9CgoJCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQkJcS50YWlsID0gcS5yaWdodE1hcmdpbgoJCX0KCX0KCglxLmZ1bGwgPSBmYWxzZQoKCWlmIHEudmVyYm9zZSB7CgkJbG9nLlByaW50ZigiQWxsb2NhdGVkIG5ldyBxdWV1ZSBpbiAlczsgQ2FwYWNpdHk6ICVkIFxuIiwgdGltZS5TaW5jZShzdGFydCksIHEuY2FwYWNpdHkpCgl9Cn0KCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIHB1c2goZGF0YSBbXWJ5dGUsIGxlbiBpbnQpIHsKCWhlYWRlckVudHJ5U2l6ZSA6PSBiaW5hcnkuUHV0VXZhcmludChxLmhlYWRlckJ1ZmZlciwgdWludDY0KGxlbikpCglxLmNvcHkocS5oZWFkZXJCdWZmZXIsIGhlYWRlckVudHJ5U2l6ZSkKCglxLmNvcHkoZGF0YSwgbGVuLWhlYWRlckVudHJ5U2l6ZSkKCglpZiBxLnRhaWwgPiBxLmhlYWQgewoJCXEucmlnaHRNYXJnaW4gPSBxLnRhaWwKCX0KCWlmIHEudGFpbCA9PSBxLmhlYWQgewoJCXEuZnVsbCA9IHRydWUKCX0KCglxLmNvdW50KysKfQoKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgY29weShkYXRhIFtdYnl0ZSwgbGVuIGludCkgewoJcS50YWlsICs9IGNvcHkocS5hcnJheVtxLnRhaWw6XSwgZGF0YVs6bGVuXSkKfQoKLy8gUG9wIHJlYWRzIHRoZSBvbGRlc3QgZW50cnkgZnJvbSBxdWV1ZSBhbmQgbW92ZXMgaGVhZCBwb2ludGVyIHRvIHRoZSBuZXh0IG9uZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBQb3AoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgYmxvY2tTaXplLCBlcnIgOj0gcS5wZWVrKHEuaGVhZCkKCWlmIGVyciAhPSBuaWwgewoJCXJldHVybiBuaWwsIGVycgoJfQoKCXEuaGVhZCArPSBibG9ja1NpemUKCXEuY291bnQtLQoKCWlmIHEuaGVhZCA9PSBxLnJpZ2h0TWFyZ2luIHsKCQlxLmhlYWQgPSBsZWZ0TWFyZ2luSW5kZXgKCQlpZiBxLnRhaWwgPT0gcS5yaWdodE1hcmdpbiB7CgkJCXEudGFpbCA9IGxlZnRNYXJnaW5JbmRleAoJCX0KCQlxLnJpZ2h0TWFyZ2luID0gcS50YWlsCgl9CgoJcS5mdWxsID0gZmFsc2UKCglyZXR1cm4gZGF0YSwgbmlsCn0KCi8vIFBlZWsgcmVhZHMgdGhlIG9sZGVzdCBlbnRyeSBmcm9tIGxpc3Qgd2l0aG91dCBtb3ZpbmcgaGVhZCBwb2ludGVyCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIFBlZWsoKSAoW11ieXRlLCBlcnJvcikgewoJZGF0YSwgXywgZXJyIDo9IHEucGVlayhxLmhlYWQpCglyZXR1cm4gZGF0YSwgZXJyCn0KCi8vIEdldCByZWFkcyBlbnRyeSBmcm9tIGluZGV4CmZ1bmMgKHEgKkJ5dGVzUXVldWUpIEdldChpbmRleCBpbnQpIChbXWJ5dGUsIGVycm9yKSB7CglkYXRhLCBfLCBlcnIgOj0gcS5wZWVrKGluZGV4KQoJcmV0dXJuIGRhdGEsIGVycgp9CgovLyBDaGVja0dldCBjaGVja3MgaWYgYW4gZW50cnkgY2FuIGJlIHJlYWQgZnJvbSBpbmRleApmdW5jIChxICpCeXRlc1F1ZXVlKSBDaGVja0dldChpbmRleCBpbnQpIGVycm9yIHsKCXJldHVybiBxLnBlZWtDaGVja0VycihpbmRleCkKfQoKLy8gQ2FwYWNpdHkgcmV0dXJucyBudW1iZXIgb2YgYWxsb2NhdGVkIGJ5dGVzIGZvciBxdWV1ZQpmdW5jIChxICpCeXRlc1F1ZXVlKSBDYXBhY2l0eSgpIGludCB7CglyZXR1cm4gcS5jYXBhY2l0eQp9CgovLyBMZW4gcmV0dXJucyBudW1iZXIgb2YgZW50cmllcyBrZXB0IGluIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIExlbigpIGludCB7CglyZXR1cm4gcS5jb3VudAp9CgovLyBFcnJvciByZXR1cm5zIGVycm9yIG1lc3NhZ2UKZnVuYyAoZSAqcXVldWVFcnJvcikgRXJyb3IoKSBzdHJpbmcgewoJcmV0dXJuIGUubWVzc2FnZQp9CgovLyBwZWVrQ2hlY2tFcnIgaXMgaWRlbnRpY2FsIHRvIHBlZWssIGJ1dCBkb2VzIG5vdCBhY3R1YWxseSByZXR1cm4gYW55IGRhdGEKZnVuYyAocSAqQnl0ZXNRdWV1ZSkgcGVla0NoZWNrRXJyKGluZGV4IGludCkgZXJyb3IgewoKCWlmIHEuY291bnQgPT0gMCB7CgkJcmV0dXJuIGVyckVtcHR5UXVldWUKCX0KCglpZiBpbmRleCA8PSAwIHsKCQlyZXR1cm4gZXJySW52YWxpZEluZGV4Cgl9CgoJaWYgaW5kZXggPj0gbGVuKHEuYXJyYXkpIHsKCQlyZXR1cm4gZXJySW5kZXhPdXRPZkJvdW5kcwoJfQoJcmV0dXJuIG5pbAp9CgovLyBwZWVrIHJldHVybnMgdGhlIGRhdGEgZnJvbSBpbmRleCBhbmQgdGhlIG51bWJlciBvZiBieXRlcyB0byBlbmNvZGUgdGhlIGxlbmd0aCBvZiB0aGUgZGF0YSBpbiB1dmFyaW50IGZvcm1hdApmdW5jIChxICpCeXRlc1F1ZXVlKSBwZWVrKGluZGV4IGludCkgKFtdYnl0ZSwgaW50LCBlcnJvcikgewoJZXJyIDo9IHEucGVla0NoZWNrRXJyKGluZGV4KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgMCwgZXJyCgl9CgoJYmxvY2tTaXplLCBuIDo9IGJpbmFyeS5VdmFyaW50KHEuYXJyYXlbaW5kZXg6XSkKCXJldHVybiBxLmFycmF5W2luZGV4K24gOiBpbmRleCtpbnQoYmxvY2tTaXplKV0sIGludChibG9ja1NpemUpLCBuaWwKfQoKLy8gY2FuSW5zZXJ0QWZ0ZXJUYWlsIHJldHVybnMgdHJ1ZSBpZiBpdCdzIHBvc3NpYmxlIHRvIGluc2VydCBhbiBlbnRyeSBvZiBzaXplIG9mIG5lZWQgYWZ0ZXIgdGhlIHRhaWwgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEFmdGVyVGFpbChuZWVkIGludCkgYm9vbCB7CglpZiBxLmZ1bGwgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgcS50YWlsID49IHEuaGVhZCB7CgkJcmV0dXJuIHEuY2FwYWNpdHktcS50YWlsID49IG5lZWQKCX0KCS8vIDEuIHRoZXJlIGlzIGV4YWN0bHkgbmVlZCBieXRlcyBiZXR3ZWVuIGhlYWQgYW5kIHRhaWwsIHNvIHdlIGRvIG5vdCBuZWVkCgkvLyB0byByZXNlcnZlIGV4dHJhIHNwYWNlIGZvciBhIHBvdGVudGlhbCBlbXB0eSBlbnRyeSB3aGVuIHJlYWxsb2MgdGhpcyBxdWV1ZQoJLy8gMi4gc3RpbGwgaGF2ZSB1bnVzZWQgc3BhY2UgYmV0d2VlbiB0YWlsIGFuZCBoZWFkLCB0aGVuIHdlIG11c3QgcmVzZXJ2ZQoJLy8gYXQgbGVhc3QgaGVhZGVyRW50cnlTaXplIGJ5dGVzIHNvIHdlIGNhbiBwdXQgYW4gZW1wdHkgZW50cnkKCXJldHVybiBxLmhlYWQtcS50YWlsID09IG5lZWQgfHwgcS5oZWFkLXEudGFpbCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCn0KCi8vIGNhbkluc2VydEJlZm9yZUhlYWQgcmV0dXJucyB0cnVlIGlmIGl0J3MgcG9zc2libGUgdG8gaW5zZXJ0IGFuIGVudHJ5IG9mIHNpemUgb2YgbmVlZCBiZWZvcmUgdGhlIGhlYWQgb2YgdGhlIHF1ZXVlCmZ1bmMgKHEgKkJ5dGVzUXVldWUpIGNhbkluc2VydEJlZm9yZUhlYWQobmVlZCBpbnQpIGJvb2wgewoJaWYgcS5mdWxsIHsKCQlyZXR1cm4gZmFsc2UKCX0KCWlmIHEudGFpbCA+PSBxLmhlYWQgewoJCXJldHVybiBxLmhlYWQtbGVmdE1hcmdpbkluZGV4ID09IG5lZWQgfHwgcS5oZWFkLWxlZnRNYXJnaW5JbmRleCA+PSBuZWVkK21pbmltdW1IZWFkZXJTaXplCgl9CglyZXR1cm4gcS5oZWFkLXEudGFpbCA9PSBuZWVkIHx8IHEuaGVhZC1xLnRhaWwgPj0gbmVlZCttaW5pbXVtSGVhZGVyU2l6ZQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..c189b3a73929fc367cd37924465390f5531c1080 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_assign__ohzataa4/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "7163170bbe03e1df2ff64d38560cb60318333ad212bb91be4345cd2776b62481", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..39bead972423f3ca7203470d123f33cb1dbb8637 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/iterator.go @@ -0,0 +1,136 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..262f2bf46fc32d865b1443abf761edbf5d61b1bc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/instruction.md @@ -0,0 +1,40 @@ +Iterator skips entries within current shard + +#### Description + +The iterator is not properly iterating through all entries within the current shard before moving to the next shard. It appears to skip remaining entries in the current shard and jumps directly to the next shard. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + cache, _ := bigcache.NewBigCache(bigcache.DefaultConfig(10 * time.Minute)) + + // Add multiple entries to ensure they're distributed across shards + for i := 0; i < 1000; i++ { + key := fmt.Sprintf("key%d", i) + value := fmt.Sprintf("value%d", i) + cache.Set(key, []byte(value)) + } + + // Count entries using iterator + iterator := cache.Iterator() + count := 0 + for iterator.SetNext() { + count++ + } + + fmt.Printf("Expected: 1000, Actual: %d\n", count) +} +``` + +The iterator returns significantly fewer entries than expected, suggesting it's not properly iterating through all entries within each shard. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..b5a3e280b7f2d4840f7b2052c716ea773a8e6520 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "ea6c1e269890f7699111775cd6b13108b6797c85cb74fc5d6d43d4c96b63d1a4", + "size": 3064 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "production/runtime-images-v1/resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "d8ab72fd244331ba326828cbeff5192a0a60e83e7b0a9c0cdaad1f0c58643f69", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "1fd617c0293cbea1909e0a3e19d70d79a874de3933e3447df651669f56708846", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "fcfe9d3e17115a0adfb954df7d6d171b87b3859d0a382c0836f068468293f0b5", + "is_fork": true, + "learner_path": "tasks/1044d32bcd522bca655abe65/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/6bc50c8f86c8e43adcb2fc7f2b68d3820e916e79/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "d62740ce63f4d35ce3248ea739bb787e2a20eb703b1662acc0cc7719065adf0f", + "provenance_path": "tasks/1044d32bcd522bca655abe65/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "6bc50c8f86c8e43adcb2fc7f2b68d3820e916e79", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "d72555fe052bde18ce4ab3f77a8e1baae7d63673", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237", + "task_sha256": "67f7d546a1c200ff361d38746177a2044981b677208c8b998ae53990c67fef00", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "369dbe081362cf4edc3d41e7b392953a575060caab93543d33b98c7ff84d120e", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7953c2f5e16c548afb5dfc60d3b6b2926811fdbc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"iterator.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJzeW5jIgopCgp0eXBlIGl0ZXJhdG9yRXJyb3Igc3RyaW5nCgpmdW5jIChlIGl0ZXJhdG9yRXJyb3IpIEVycm9yKCkgc3RyaW5nIHsKCXJldHVybiBzdHJpbmcoZSkKfQoKLy8gRXJySW52YWxpZEl0ZXJhdG9yU3RhdGUgaXMgcmVwb3J0ZWQgd2hlbiBpdGVyYXRvciBpcyBpbiBpbnZhbGlkIHN0YXRlCmNvbnN0IEVyckludmFsaWRJdGVyYXRvclN0YXRlID0gaXRlcmF0b3JFcnJvcigiSXRlcmF0b3IgaXMgaW4gaW52YWxpZCBzdGF0ZS4gVXNlIFNldE5leHQoKSB0byBtb3ZlIHRvIG5leHQgcG9zaXRpb24iKQoKLy8gRXJyQ2Fubm90UmV0cmlldmVFbnRyeSBpcyByZXBvcnRlZCB3aGVuIGVudHJ5IGNhbm5vdCBiZSByZXRyaWV2ZWQgZnJvbSB1bmRlcmx5aW5nCmNvbnN0IEVyckNhbm5vdFJldHJpZXZlRW50cnkgPSBpdGVyYXRvckVycm9yKCJDb3VsZCBub3QgcmV0cmlldmUgZW50cnkgZnJvbSBjYWNoZSIpCgp2YXIgZW1wdHlFbnRyeUluZm8gPSBFbnRyeUluZm97fQoKLy8gRW50cnlJbmZvIGhvbGRzIGluZm9ybWF0aW9ucyBhYm91dCBlbnRyeSBpbiB0aGUgY2FjaGUKdHlwZSBFbnRyeUluZm8gc3RydWN0IHsKCXRpbWVzdGFtcCB1aW50NjQKCWhhc2ggICAgICB1aW50NjQKCWtleSAgICAgICBzdHJpbmcKCXZhbHVlICAgICBbXWJ5dGUKCWVyciAgICAgICBlcnJvcgp9CgovLyBLZXkgcmV0dXJucyBlbnRyeSdzIHVuZGVybHlpbmcga2V5CmZ1bmMgKGUgRW50cnlJbmZvKSBLZXkoKSBzdHJpbmcgewoJcmV0dXJuIGUua2V5Cn0KCi8vIEhhc2ggcmV0dXJucyBlbnRyeSdzIGhhc2ggdmFsdWUKZnVuYyAoZSBFbnRyeUluZm8pIEhhc2goKSB1aW50NjQgewoJcmV0dXJuIGUuaGFzaAp9CgovLyBUaW1lc3RhbXAgcmV0dXJucyBlbnRyeSdzIHRpbWVzdGFtcCAodGltZSBvZiBpbnNlcnRpb24pCmZ1bmMgKGUgRW50cnlJbmZvKSBUaW1lc3RhbXAoKSB1aW50NjQgewoJcmV0dXJuIGUudGltZXN0YW1wCn0KCi8vIFZhbHVlIHJldHVybnMgZW50cnkncyB1bmRlcmx5aW5nIHZhbHVlCmZ1bmMgKGUgRW50cnlJbmZvKSBWYWx1ZSgpIFtdYnl0ZSB7CglyZXR1cm4gZS52YWx1ZQp9CgovLyBFbnRyeUluZm9JdGVyYXRvciBhbGxvd3MgdG8gaXRlcmF0ZSBvdmVyIGVudHJpZXMgaW4gdGhlIGNhY2hlCnR5cGUgRW50cnlJbmZvSXRlcmF0b3Igc3RydWN0IHsKCW11dGV4ICAgICAgICAgICAgc3luYy5NdXRleAoJY2FjaGUgICAgICAgICAgICAqQmlnQ2FjaGUKCWN1cnJlbnRTaGFyZCAgICAgaW50CgljdXJyZW50SW5kZXggICAgIGludAoJY3VycmVudEVudHJ5SW5mbyBFbnRyeUluZm8KCWVsZW1lbnRzICAgICAgICAgW111aW50NjQKCWVsZW1lbnRzQ291bnQgICAgaW50Cgl2YWxpZCAgICAgICAgICAgIGJvb2wKfQoKLy8gU2V0TmV4dCBtb3ZlcyB0byBuZXh0IGVsZW1lbnQgYW5kIHJldHVybnMgdHJ1ZSBpZiBpdCBleGlzdHMuCmZ1bmMgKGl0ICpFbnRyeUluZm9JdGVyYXRvcikgU2V0TmV4dCgpIGJvb2wgewoJaXQubXV0ZXguTG9jaygpCgoJaXQudmFsaWQgPSBmYWxzZQoJaXQuY3VycmVudEluZGV4KysKCglpZiBpdC5lbGVtZW50c0NvdW50ID4gaXQuY3VycmVudEluZGV4IHsKCQlpdC52YWxpZCA9IHRydWUKCgkJZW1wdHkgOj0gaXQuc2V0Q3VycmVudEVudHJ5KCkKCQlpdC5tdXRleC5VbmxvY2soKQoKCQlpZiBlbXB0eSB7CgkJCXJldHVybiBpdC5TZXROZXh0KCkKCQl9CgkJcmV0dXJuIHRydWUKCX0KCglmb3IgaSA6PSBpdC5jdXJyZW50U2hhcmQgKyAxOyBpIDwgaXQuY2FjaGUuY29uZmlnLlNoYXJkczsgaSsrIHsKCQlpdC5lbGVtZW50cywgaXQuZWxlbWVudHNDb3VudCA9IGl0LmNhY2hlLnNoYXJkc1tpXS5jb3B5SGFzaGVkS2V5cygpCgoJCS8vIE5vbiBlbXB0eSBzaGFyZCAtIHN0aWNrIHdpdGggaXQKCQlpZiBpdC5lbGVtZW50c0NvdW50ID4gMCB7CgkJCWl0LmN1cnJlbnRJbmRleCA9IDAKCQkJaXQuY3VycmVudFNoYXJkID0gaQoJCQlpdC52YWxpZCA9IHRydWUKCgkJCWVtcHR5IDo9IGl0LnNldEN1cnJlbnRFbnRyeSgpCgkJCWl0Lm11dGV4LlVubG9jaygpCgoJCQlpZiBlbXB0eSB7CgkJCQlyZXR1cm4gaXQuU2V0TmV4dCgpCgkJCX0KCQkJcmV0dXJuIHRydWUKCQl9Cgl9CglpdC5tdXRleC5VbmxvY2soKQoJcmV0dXJuIGZhbHNlCn0KCmZ1bmMgKGl0ICpFbnRyeUluZm9JdGVyYXRvcikgc2V0Q3VycmVudEVudHJ5KCkgYm9vbCB7Cgl2YXIgZW50cnlOb3RGb3VuZCA9IGZhbHNlCgllbnRyeSwgZXJyIDo9IGl0LmNhY2hlLnNoYXJkc1tpdC5jdXJyZW50U2hhcmRdLmdldEVudHJ5KGl0LmVsZW1lbnRzW2l0LmN1cnJlbnRJbmRleF0pCgoJaWYgZXJyID09IEVyckVudHJ5Tm90Rm91bmQgewoJCWl0LmN1cnJlbnRFbnRyeUluZm8gPSBlbXB0eUVudHJ5SW5mbwoJCWVudHJ5Tm90Rm91bmQgPSB0cnVlCgl9IGVsc2UgaWYgZXJyICE9IG5pbCB7CgkJaXQuY3VycmVudEVudHJ5SW5mbyA9IEVudHJ5SW5mb3sKCQkJZXJyOiBlcnIsCgkJfQoJfSBlbHNlIHsKCQlpdC5jdXJyZW50RW50cnlJbmZvID0gRW50cnlJbmZvewoJCQl0aW1lc3RhbXA6IHJlYWRUaW1lc3RhbXBGcm9tRW50cnkoZW50cnkpLAoJCQloYXNoOiAgICAgIHJlYWRIYXNoRnJvbUVudHJ5KGVudHJ5KSwKCQkJa2V5OiAgICAgICByZWFkS2V5RnJvbUVudHJ5KGVudHJ5KSwKCQkJdmFsdWU6ICAgICByZWFkRW50cnkoZW50cnkpLAoJCQllcnI6ICAgICAgIGVyciwKCQl9Cgl9CgoJcmV0dXJuIGVudHJ5Tm90Rm91bmQKfQoKZnVuYyBuZXdJdGVyYXRvcihjYWNoZSAqQmlnQ2FjaGUpICpFbnRyeUluZm9JdGVyYXRvciB7CgllbGVtZW50cywgY291bnQgOj0gY2FjaGUuc2hhcmRzWzBdLmNvcHlIYXNoZWRLZXlzKCkKCglyZXR1cm4gJkVudHJ5SW5mb0l0ZXJhdG9yewoJCWNhY2hlOiAgICAgICAgIGNhY2hlLAoJCWN1cnJlbnRTaGFyZDogIDAsCgkJY3VycmVudEluZGV4OiAgLTEsCgkJZWxlbWVudHM6ICAgICAgZWxlbWVudHMsCgkJZWxlbWVudHNDb3VudDogY291bnQsCgl9Cn0KCi8vIFZhbHVlIHJldHVybnMgY3VycmVudCB2YWx1ZSBmcm9tIHRoZSBpdGVyYXRvcgpmdW5jIChpdCAqRW50cnlJbmZvSXRlcmF0b3IpIFZhbHVlKCkgKEVudHJ5SW5mbywgZXJyb3IpIHsKCWlmICFpdC52YWxpZCB7CgkJcmV0dXJuIGVtcHR5RW50cnlJbmZvLCBFcnJJbnZhbGlkSXRlcmF0b3JTdGF0ZQoJfQoKCXJldHVybiBpdC5jdXJyZW50RW50cnlJbmZvLCBpdC5jdXJyZW50RW50cnlJbmZvLmVycgp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..897859c254ae145cadd0a31759a0cebab50ba1b4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:59faf97ddd1e4a7c29c87a1ac2552bbbd1c3211347d8c9992d3c343a8316b5eb" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..140eec03172b716e1548921152a7bf67742abca2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/manifest.json @@ -0,0 +1,561 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithConcurrentUpdate" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIterator" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveWithReasonCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNilValueCaching" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotFound" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorInInvalidState" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEvictionShouldEvictOnlyFromUpdatedShard" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithMostShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEviction" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_allocateAdditionalMemoryLeadPanic" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfoCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithAllShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotPresent" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Before_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/After_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheRestStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/Shards_number_must_be_power_of_two" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntriesInWindow_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntrySize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/HardMaxCacheSize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestConstructCacheWithDefaultHasher" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestHashCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestGetOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveEntriesWhenShardIsFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryBiggerThanMaxShardSizeError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRetrievingEntryShouldCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveGetEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOldestEntryDeletionWhenMaxCacheSizeIsReached" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestIterateOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDel" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndReadParallelSameKeyWithStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheInitialCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDelRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCleanShouldEvictAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestParallelSetAndIteration" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example_custom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..bcb0756104970e5d84ef410c6422ee35746fd680 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__aqxt9237/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "07a61fb4d374714d3327564bd87f17ad6c3203f559fd27edd27d880a0adb4f51", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..b3aa37bb37b2414528a6082ad91557a7903c5df1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bigcache.go @@ -0,0 +1,276 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + if c.config.onRemoveFilter == 0 || (1< 0 { + c.config.OnRemoveWithReason(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry), reason) + } +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..da90f0466c52b748877695baa5fd60e9d9482ec6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/shard.go @@ -0,0 +1,452 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9be28477323702bfff30ca7278d28a34bb5ddd92 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/instruction.md @@ -0,0 +1,41 @@ +Cache initial capacity calculation incorrect when MaxShardSize is set + +#### Description + +When creating a cache with a MaxShardSize configuration, the initial capacity calculation is not respecting the maximum shard size limit. The cache is allocating more memory than expected for the initial capacity. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "github.com/allegro/bigcache/v3" + "time" +) + +func main() { + config := bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + HardMaxCacheSize: 8192, + } + + cache, err := bigcache.NewBigCache(config) + if err != nil { + panic(err) + } + + // Expected initial capacity should respect MaxShardSize + // but actual capacity is double what's expected + fmt.Printf("Cache created with unexpected initial capacity\n") + _ = cache +} +``` + +The issue appears when the cache configuration includes a MaxShardSize setting - the initial bytes queue capacity is not being properly capped to the maximum shard size, resulting in higher than expected memory allocation during cache initialization. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..f26ad76d4556a9756778ab190031475ee23fa85c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "113b7f1a2477fedb959e63f334111e49d6d7b81becdcd08c9c61fa4c56ddb915", + "size": 7884 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "e61fc6f2fb5928b5103ab26f676696c5da3f5ed6619b8d38ef2e0085a2c2f6ea", + "size": 10624 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "production/runtime-images-v1/resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "196003bf9ec520552be32695b49c007a0ea19198fde6bb4e7ae504571a4996fc", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "5ea49221bc53c67608ecf0d867477d4296cc639c581064884ae290fb5e0b6633", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "33eaa2322611bb7a52b36074886623cff0997bbbf1b95b046cf08d5cfe2ada0b", + "is_fork": true, + "learner_path": "tasks/6b1de74d03796574f25212f2/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/6b0d3faa42e38f8ec5f3dce56d0b797d797c4174/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "5f216ef0b4a50a68801cc43ff4af060d3fb4d13a3193532c70036f85bfe1be56", + "provenance_path": "tasks/6b1de74d03796574f25212f2/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "6b0d3faa42e38f8ec5f3dce56d0b797d797c4174", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "96c1fce8f13ed50e17925641996b3e285841606e", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9", + "task_sha256": "b56a8434488787e447e61a6976a81acb7233baf159a94af588e70ac26c72491d", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "0d72f058f5e7db50c0f8dcff3864ccbf10f5ae4653f76d83d1ed86a57a12b422", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a73356f1e7514155ea2de6f64b67d4a1c9d3878 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"shard.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJlcnJvcnMiCgkic3luYyIKCSJzeW5jL2F0b21pYyIKCgkiZ2l0aHViLmNvbS9hbGxlZ3JvL2JpZ2NhY2hlL3YzL3F1ZXVlIgopCgp0eXBlIG9uUmVtb3ZlQ2FsbGJhY2sgZnVuYyh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKQoKLy8gTWV0YWRhdGEgY29udGFpbnMgaW5mb3JtYXRpb24gb2YgYSBzcGVjaWZpYyBlbnRyeQp0eXBlIE1ldGFkYXRhIHN0cnVjdCB7CglSZXF1ZXN0Q291bnQgdWludDMyCn0KCnR5cGUgY2FjaGVTaGFyZCBzdHJ1Y3QgewoJaGFzaG1hcCAgICAgbWFwW3VpbnQ2NF11aW50NjQKCWVudHJpZXMgICAgIHF1ZXVlLkJ5dGVzUXVldWUKCWxvY2sgICAgICAgIHN5bmMuUldNdXRleAoJZW50cnlCdWZmZXIgW11ieXRlCglvblJlbW92ZSAgICBvblJlbW92ZUNhbGxiYWNrCgoJaXNWZXJib3NlICAgIGJvb2wKCXN0YXRzRW5hYmxlZCBib29sCglsb2dnZXIgICAgICAgTG9nZ2VyCgljbG9jayAgICAgICAgY2xvY2sKCWxpZmVXaW5kb3cgICB1aW50NjQKCgloYXNobWFwU3RhdHMgbWFwW3VpbnQ2NF11aW50MzIKCXN0YXRzICAgICAgICBTdGF0cwoJY2xlYW5FbmFibGVkIGJvb2wKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZ2V0V2l0aEluZm8oa2V5IHN0cmluZywgaGFzaGVkS2V5IHVpbnQ2NCkgKGVudHJ5IFtdYnl0ZSwgcmVzcCBSZXNwb25zZSwgZXJyIGVycm9yKSB7CgljdXJyZW50VGltZSA6PSB1aW50NjQocy5jbG9jay5FcG9jaCgpKQoJcy5sb2NrLlJMb2NrKCkKCXdyYXBwZWRFbnRyeSwgZXJyIDo9IHMuZ2V0V3JhcHBlZEVudHJ5KGhhc2hlZEtleSkKCWlmIGVyciAhPSBuaWwgewoJCXMubG9jay5SVW5sb2NrKCkKCQlyZXR1cm4gbmlsLCByZXNwLCBlcnIKCX0KCWlmIGVudHJ5S2V5IDo9IHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KTsga2V5ICE9IGVudHJ5S2V5IHsKCQlzLmxvY2suUlVubG9jaygpCgkJcy5jb2xsaXNpb24oKQoJCWlmIHMuaXNWZXJib3NlIHsKCQkJcy5sb2dnZXIuUHJpbnRmKCJDb2xsaXNpb24gZGV0ZWN0ZWQuIEJvdGggJXEgYW5kICVxIGhhdmUgdGhlIHNhbWUgaGFzaCAleCIsIGtleSwgZW50cnlLZXksIGhhc2hlZEtleSkKCQl9CgkJcmV0dXJuIG5pbCwgcmVzcCwgRXJyRW50cnlOb3RGb3VuZAoJfQoKCWVudHJ5ID0gcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkKCWlmIHMuaXNFeHBpcmVkKHdyYXBwZWRFbnRyeSwgY3VycmVudFRpbWUpIHsKCQlyZXNwLkVudHJ5U3RhdHVzID0gRXhwaXJlZAoJfQoJcy5sb2NrLlJVbmxvY2soKQoJcy5oaXQoaGFzaGVkS2V5KQoJcmV0dXJuIGVudHJ5LCByZXNwLCBuaWwKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZ2V0KGtleSBzdHJpbmcsIGhhc2hlZEtleSB1aW50NjQpIChbXWJ5dGUsIGVycm9yKSB7CglzLmxvY2suUkxvY2soKQoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJaWYgZXJyICE9IG5pbCB7CgkJcy5sb2NrLlJVbmxvY2soKQoJCXJldHVybiBuaWwsIGVycgoJfQoJaWYgZW50cnlLZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpOyBrZXkgIT0gZW50cnlLZXkgewoJCXMubG9jay5SVW5sb2NrKCkKCQlzLmNvbGxpc2lvbigpCgkJaWYgcy5pc1ZlcmJvc2UgewoJCQlzLmxvZ2dlci5QcmludGYoIkNvbGxpc2lvbiBkZXRlY3RlZC4gQm90aCAlcSBhbmQgJXEgaGF2ZSB0aGUgc2FtZSBoYXNoICV4Iiwga2V5LCBlbnRyeUtleSwgaGFzaGVkS2V5KQoJCX0KCQlyZXR1cm4gbmlsLCBFcnJFbnRyeU5vdEZvdW5kCgl9CgllbnRyeSA6PSByZWFkRW50cnkod3JhcHBlZEVudHJ5KQoJcy5sb2NrLlJVbmxvY2soKQoJcy5oaXQoaGFzaGVkS2V5KQoKCXJldHVybiBlbnRyeSwgbmlsCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldFdyYXBwZWRFbnRyeShoYXNoZWRLZXkgdWludDY0KSAoW11ieXRlLCBlcnJvcikgewoJaXRlbUluZGV4IDo9IHMuaGFzaG1hcFtoYXNoZWRLZXldCgoJaWYgaXRlbUluZGV4ID09IDAgewoJCXMubWlzcygpCgkJcmV0dXJuIG5pbCwgRXJyRW50cnlOb3RGb3VuZAoJfQoKCXdyYXBwZWRFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KGl0ZW1JbmRleCkpCglpZiBlcnIgIT0gbmlsIHsKCQlzLm1pc3MoKQoJCXJldHVybiBuaWwsIGVycgoJfQoKCXJldHVybiB3cmFwcGVkRW50cnksIGVycgp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBnZXRWYWxpZFdyYXBFbnRyeShrZXkgc3RyaW5nLCBoYXNoZWRLZXkgdWludDY0KSAoW11ieXRlLCBlcnJvcikgewoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJaWYgZXJyICE9IG5pbCB7CgkJcmV0dXJuIG5pbCwgZXJyCgl9CgoJaWYgIWNvbXBhcmVLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5LCBrZXkpIHsKCQlzLmNvbGxpc2lvbigpCgkJaWYgcy5pc1ZlcmJvc2UgewoJCQlzLmxvZ2dlci5QcmludGYoIkNvbGxpc2lvbiBkZXRlY3RlZC4gQm90aCAlcSBhbmQgJXEgaGF2ZSB0aGUgc2FtZSBoYXNoICV4Iiwga2V5LCByZWFkS2V5RnJvbUVudHJ5KHdyYXBwZWRFbnRyeSksIGhhc2hlZEtleSkKCQl9CgoJCXJldHVybiBuaWwsIEVyckVudHJ5Tm90Rm91bmQKCX0KCXMuaGl0V2l0aG91dExvY2soaGFzaGVkS2V5KQoKCXJldHVybiB3cmFwcGVkRW50cnksIG5pbAp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBzZXQoa2V5IHN0cmluZywgaGFzaGVkS2V5IHVpbnQ2NCwgZW50cnkgW11ieXRlKSBlcnJvciB7CgljdXJyZW50VGltZXN0YW1wIDo9IHVpbnQ2NChzLmNsb2NrLkVwb2NoKCkpCgoJcy5sb2NrLkxvY2soKQoKCWlmIHByZXZpb3VzSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV07IHByZXZpb3VzSW5kZXggIT0gMCB7CgkJaWYgcHJldmlvdXNFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KHByZXZpb3VzSW5kZXgpKTsgZXJyID09IG5pbCB7CgkJCXJlc2V0SGFzaEZyb21FbnRyeShwcmV2aW91c0VudHJ5KQoJCQkvL3JlbW92ZSBoYXNoa2V5CgkJCWRlbGV0ZShzLmhhc2htYXAsIGhhc2hlZEtleSkKCQl9Cgl9CgoJaWYgIXMuY2xlYW5FbmFibGVkIHsKCQlpZiBvbGRlc3RFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5QZWVrKCk7IGVyciA9PSBuaWwgewoJCQlzLm9uRXZpY3Qob2xkZXN0RW50cnksIGN1cnJlbnRUaW1lc3RhbXAsIHMucmVtb3ZlT2xkZXN0RW50cnkpCgkJfQoJfQoKCXcgOj0gd3JhcEVudHJ5KGN1cnJlbnRUaW1lc3RhbXAsIGhhc2hlZEtleSwga2V5LCBlbnRyeSwgJnMuZW50cnlCdWZmZXIpCgoJZm9yIHsKCQlpZiBpbmRleCwgZXJyIDo9IHMuZW50cmllcy5QdXNoKHcpOyBlcnIgPT0gbmlsIHsKCQkJcy5oYXNobWFwW2hhc2hlZEtleV0gPSB1aW50NjQoaW5kZXgpCgkJCXMubG9jay5VbmxvY2soKQoJCQlyZXR1cm4gbmlsCgkJfQoJCWlmIHMucmVtb3ZlT2xkZXN0RW50cnkoTm9TcGFjZSkgIT0gbmlsIHsKCQkJcy5sb2NrLlVubG9jaygpCgkJCXJldHVybiBlcnJvcnMuTmV3KCJlbnRyeSBpcyBiaWdnZXIgdGhhbiBtYXggc2hhcmQgc2l6ZSIpCgkJfQoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBhZGROZXdXaXRob3V0TG9jayhrZXkgc3RyaW5nLCBoYXNoZWRLZXkgdWludDY0LCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWN1cnJlbnRUaW1lc3RhbXAgOj0gdWludDY0KHMuY2xvY2suRXBvY2goKSkKCglpZiAhcy5jbGVhbkVuYWJsZWQgewoJCWlmIG9sZGVzdEVudHJ5LCBlcnIgOj0gcy5lbnRyaWVzLlBlZWsoKTsgZXJyID09IG5pbCB7CgkJCXMub25FdmljdChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCwgcy5yZW1vdmVPbGRlc3RFbnRyeSkKCQl9Cgl9CgoJdyA6PSB3cmFwRW50cnkoY3VycmVudFRpbWVzdGFtcCwgaGFzaGVkS2V5LCBrZXksIGVudHJ5LCAmcy5lbnRyeUJ1ZmZlcikKCglmb3IgewoJCWlmIGluZGV4LCBlcnIgOj0gcy5lbnRyaWVzLlB1c2godyk7IGVyciA9PSBuaWwgewoJCQlzLmhhc2htYXBbaGFzaGVkS2V5XSA9IHVpbnQ2NChpbmRleCkKCQkJcmV0dXJuIG5pbAoJCX0KCQlpZiBzLnJlbW92ZU9sZGVzdEVudHJ5KE5vU3BhY2UpICE9IG5pbCB7CgkJCXJldHVybiBlcnJvcnMuTmV3KCJlbnRyeSBpcyBiaWdnZXIgdGhhbiBtYXggc2hhcmQgc2l6ZSIpCgkJfQoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBzZXRXcmFwcGVkRW50cnlXaXRob3V0TG9jayhjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgdyBbXWJ5dGUsIGhhc2hlZEtleSB1aW50NjQpIGVycm9yIHsKCWlmIHByZXZpb3VzSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV07IHByZXZpb3VzSW5kZXggIT0gMCB7CgkJaWYgcHJldmlvdXNFbnRyeSwgZXJyIDo9IHMuZW50cmllcy5HZXQoaW50KHByZXZpb3VzSW5kZXgpKTsgZXJyID09IG5pbCB7CgkJCXJlc2V0SGFzaEZyb21FbnRyeShwcmV2aW91c0VudHJ5KQoJCX0KCX0KCglpZiAhcy5jbGVhbkVuYWJsZWQgewoJCWlmIG9sZGVzdEVudHJ5LCBlcnIgOj0gcy5lbnRyaWVzLlBlZWsoKTsgZXJyID09IG5pbCB7CgkJCXMub25FdmljdChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCwgcy5yZW1vdmVPbGRlc3RFbnRyeSkKCQl9Cgl9CgoJZm9yIHsKCQlpZiBpbmRleCwgZXJyIDo9IHMuZW50cmllcy5QdXNoKHcpOyBlcnIgPT0gbmlsIHsKCQkJcy5oYXNobWFwW2hhc2hlZEtleV0gPSB1aW50NjQoaW5kZXgpCgkJCXJldHVybiBuaWwKCQl9CgkJaWYgcy5yZW1vdmVPbGRlc3RFbnRyeShOb1NwYWNlKSAhPSBuaWwgewoJCQlyZXR1cm4gZXJyb3JzLk5ldygiZW50cnkgaXMgYmlnZ2VyIHRoYW4gbWF4IHNoYXJkIHNpemUiKQoJCX0KCX0KfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgYXBwZW5kKGtleSBzdHJpbmcsIGhhc2hlZEtleSB1aW50NjQsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJcy5sb2NrLkxvY2soKQoJd3JhcHBlZEVudHJ5LCBlcnIgOj0gcy5nZXRWYWxpZFdyYXBFbnRyeShrZXksIGhhc2hlZEtleSkKCglpZiBlcnIgPT0gRXJyRW50cnlOb3RGb3VuZCB7CgkJZXJyID0gcy5hZGROZXdXaXRob3V0TG9jayhrZXksIGhhc2hlZEtleSwgZW50cnkpCgkJcy5sb2NrLlVubG9jaygpCgkJcmV0dXJuIGVycgoJfQoJaWYgZXJyICE9IG5pbCB7CgkJcy5sb2NrLlVubG9jaygpCgkJcmV0dXJuIGVycgoJfQoKCWN1cnJlbnRUaW1lc3RhbXAgOj0gdWludDY0KHMuY2xvY2suRXBvY2goKSkKCgl3IDo9IGFwcGVuZFRvV3JhcHBlZEVudHJ5KGN1cnJlbnRUaW1lc3RhbXAsIHdyYXBwZWRFbnRyeSwgZW50cnksICZzLmVudHJ5QnVmZmVyKQoKCWVyciA9IHMuc2V0V3JhcHBlZEVudHJ5V2l0aG91dExvY2soY3VycmVudFRpbWVzdGFtcCwgdywgaGFzaGVkS2V5KQoJcy5sb2NrLlVubG9jaygpCgoJcmV0dXJuIGVycgp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBkZWwoaGFzaGVkS2V5IHVpbnQ2NCkgZXJyb3IgewoJLy8gT3B0aW1pc3RpYyBwcmUtY2hlY2sgdXNpbmcgb25seSByZWFkbG9jawoJcy5sb2NrLlJMb2NrKCkKCXsKCQlpdGVtSW5kZXggOj0gcy5oYXNobWFwW2hhc2hlZEtleV0KCgkJaWYgaXRlbUluZGV4ID09IDAgewoJCQlzLmxvY2suUlVubG9jaygpCgkJCXMuZGVsbWlzcygpCgkJCXJldHVybiBFcnJFbnRyeU5vdEZvdW5kCgkJfQoKCQlpZiBlcnIgOj0gcy5lbnRyaWVzLkNoZWNrR2V0KGludChpdGVtSW5kZXgpKTsgZXJyICE9IG5pbCB7CgkJCXMubG9jay5SVW5sb2NrKCkKCQkJcy5kZWxtaXNzKCkKCQkJcmV0dXJuIGVycgoJCX0KCX0KCXMubG9jay5SVW5sb2NrKCkKCglzLmxvY2suTG9jaygpCgl7CgkJLy8gQWZ0ZXIgb2J0YWluaW5nIHRoZSB3cml0ZWxvY2ssIHdlIG5lZWQgdG8gcmVhZCB0aGUgc2FtZSBhZ2FpbiwKCQkvLyBzaW5jZSB0aGUgZGF0YSBkZWxpdmVyZWQgZWFybGllciBtYXkgYmUgc3RhbGUgbm93CgkJaXRlbUluZGV4IDo9IHMuaGFzaG1hcFtoYXNoZWRLZXldCgoJCWlmIGl0ZW1JbmRleCA9PSAwIHsKCQkJcy5sb2NrLlVubG9jaygpCgkJCXMuZGVsbWlzcygpCgkJCXJldHVybiBFcnJFbnRyeU5vdEZvdW5kCgkJfQoKCQl3cmFwcGVkRW50cnksIGVyciA6PSBzLmVudHJpZXMuR2V0KGludChpdGVtSW5kZXgpKQoJCWlmIGVyciAhPSBuaWwgewoJCQlzLmxvY2suVW5sb2NrKCkKCQkJcy5kZWxtaXNzKCkKCQkJcmV0dXJuIGVycgoJCX0KCgkJZGVsZXRlKHMuaGFzaG1hcCwgaGFzaGVkS2V5KQoJCXMub25SZW1vdmUod3JhcHBlZEVudHJ5LCBEZWxldGVkKQoJCWlmIHMuc3RhdHNFbmFibGVkIHsKCQkJZGVsZXRlKHMuaGFzaG1hcFN0YXRzLCBoYXNoZWRLZXkpCgkJfQoJCXJlc2V0SGFzaEZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgl9CglzLmxvY2suVW5sb2NrKCkKCglzLmRlbGhpdCgpCglyZXR1cm4gbmlsCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglpZiBzLmlzRXhwaXJlZChvbGRlc3RFbnRyeSwgY3VycmVudFRpbWVzdGFtcCkgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBpc0V4cGlyZWQob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPD0gb2xkZXN0VGltZXN0YW1wIHsgLy8gaWYgY3VycmVudFRpbWVzdGFtcCA8IG9sZGVzdFRpbWVzdGFtcCwgdGhlIHJlc3VsdCB3aWxsIG91dCBvZiB1aW50NjQgbGltaXRzOwoJCXJldHVybiBmYWxzZQoJfQoJcmV0dXJuIGN1cnJlbnRUaW1lc3RhbXAtb2xkZXN0VGltZXN0YW1wID4gcy5saWZlV2luZG93Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGNsZWFuVXAoY3VycmVudFRpbWVzdGFtcCB1aW50NjQpIHsKCXMubG9jay5Mb2NrKCkKCWZvciB7CgkJaWYgb2xkZXN0RW50cnksIGVyciA6PSBzLmVudHJpZXMuUGVlaygpOyBlcnIgIT0gbmlsIHsKCQkJYnJlYWsKCQl9IGVsc2UgaWYgZXZpY3RlZCA6PSBzLm9uRXZpY3Qob2xkZXN0RW50cnksIGN1cnJlbnRUaW1lc3RhbXAsIHMucmVtb3ZlT2xkZXN0RW50cnkpOyAhZXZpY3RlZCB7CgkJCWJyZWFrCgkJfQoJfQoJcy5sb2NrLlVubG9jaygpCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldEVudHJ5KGhhc2hlZEtleSB1aW50NjQpIChbXWJ5dGUsIGVycm9yKSB7CglzLmxvY2suUkxvY2soKQoKCWVudHJ5LCBlcnIgOj0gcy5nZXRXcmFwcGVkRW50cnkoaGFzaGVkS2V5KQoJLy8gY29weSBlbnRyeQoJbmV3RW50cnkgOj0gbWFrZShbXWJ5dGUsIGxlbihlbnRyeSkpCgljb3B5KG5ld0VudHJ5LCBlbnRyeSkKCglzLmxvY2suUlVubG9jaygpCgoJcmV0dXJuIG5ld0VudHJ5LCBlcnIKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgY29weUhhc2hlZEtleXMoKSAoa2V5cyBbXXVpbnQ2NCwgbmV4dCBpbnQpIHsKCXMubG9jay5STG9jaygpCglrZXlzID0gbWFrZShbXXVpbnQ2NCwgbGVuKHMuaGFzaG1hcCkpCgoJZm9yIGtleSA6PSByYW5nZSBzLmhhc2htYXAgewoJCWtleXNbbmV4dF0gPSBrZXkKCQluZXh0KysKCX0KCglzLmxvY2suUlVubG9jaygpCglyZXR1cm4ga2V5cywgbmV4dAp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSByZW1vdmVPbGRlc3RFbnRyeShyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvciB7CglvbGRlc3QsIGVyciA6PSBzLmVudHJpZXMuUG9wKCkKCWlmIGVyciA9PSBuaWwgewoJCWhhc2ggOj0gcmVhZEhhc2hGcm9tRW50cnkob2xkZXN0KQoJCWlmIGhhc2ggPT0gMCB7CgkJCS8vIGVudHJ5IGhhcyBiZWVuIGV4cGxpY2l0bHkgZGVsZXRlZCB3aXRoIHJlc2V0SGFzaEZyb21FbnRyeSwgaWdub3JlCgkJCXJldHVybiBuaWwKCQl9CgkJZGVsZXRlKHMuaGFzaG1hcCwgaGFzaCkKCQlzLm9uUmVtb3ZlKG9sZGVzdCwgcmVhc29uKQoJCWlmIHMuc3RhdHNFbmFibGVkIHsKCQkJZGVsZXRlKHMuaGFzaG1hcFN0YXRzLCBoYXNoKQoJCX0KCQlyZXR1cm4gbmlsCgl9CglyZXR1cm4gZXJyCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIHJlc2V0KGNvbmZpZyBDb25maWcpIHsKCXMubG9jay5Mb2NrKCkKCXMuaGFzaG1hcCA9IG1ha2UobWFwW3VpbnQ2NF11aW50NjQsIGNvbmZpZy5pbml0aWFsU2hhcmRTaXplKCkpCglzLmVudHJ5QnVmZmVyID0gbWFrZShbXWJ5dGUsIGNvbmZpZy5NYXhFbnRyeVNpemUraGVhZGVyc1NpemVJbkJ5dGVzKQoJcy5lbnRyaWVzLlJlc2V0KCkKCXMubG9jay5VbmxvY2soKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSByZXNldFN0YXRzKCkgewoJcy5sb2NrLkxvY2soKQoJcy5zdGF0cyA9IFN0YXRze30KCXMubG9jay5VbmxvY2soKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBsZW4oKSBpbnQgewoJcy5sb2NrLlJMb2NrKCkKCXJlcyA6PSBsZW4ocy5oYXNobWFwKQoJcy5sb2NrLlJVbmxvY2soKQoJcmV0dXJuIHJlcwp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBjYXBhY2l0eSgpIGludCB7CglzLmxvY2suUkxvY2soKQoJcmVzIDo9IHMuZW50cmllcy5DYXBhY2l0eSgpCglzLmxvY2suUlVubG9jaygpCglyZXR1cm4gcmVzCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldFN0YXRzKCkgU3RhdHMgewoJdmFyIHN0YXRzID0gU3RhdHN7CgkJSGl0czogICAgICAgYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5IaXRzKSwKCQlNaXNzZXM6ICAgICBhdG9taWMuTG9hZEludDY0KCZzLnN0YXRzLk1pc3NlcyksCgkJRGVsSGl0czogICAgYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5EZWxIaXRzKSwKCQlEZWxNaXNzZXM6ICBhdG9taWMuTG9hZEludDY0KCZzLnN0YXRzLkRlbE1pc3NlcyksCgkJQ29sbGlzaW9uczogYXRvbWljLkxvYWRJbnQ2NCgmcy5zdGF0cy5Db2xsaXNpb25zKSwKCX0KCXJldHVybiBzdGF0cwp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBnZXRLZXlNZXRhZGF0YVdpdGhMb2NrKGtleSB1aW50NjQpIE1ldGFkYXRhIHsKCXMubG9jay5STG9jaygpCgljIDo9IHMuaGFzaG1hcFN0YXRzW2tleV0KCXMubG9jay5SVW5sb2NrKCkKCXJldHVybiBNZXRhZGF0YXsKCQlSZXF1ZXN0Q291bnQ6IGMsCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGdldEtleU1ldGFkYXRhKGtleSB1aW50NjQpIE1ldGFkYXRhIHsKCXJldHVybiBNZXRhZGF0YXsKCQlSZXF1ZXN0Q291bnQ6IHMuaGFzaG1hcFN0YXRzW2tleV0sCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGhpdChrZXkgdWludDY0KSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuSGl0cywgMSkKCWlmIHMuc3RhdHNFbmFibGVkIHsKCQlzLmxvY2suTG9jaygpCgkJcy5oYXNobWFwU3RhdHNba2V5XSsrCgkJcy5sb2NrLlVubG9jaygpCgl9Cn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGhpdFdpdGhvdXRMb2NrKGtleSB1aW50NjQpIHsKCWF0b21pYy5BZGRJbnQ2NCgmcy5zdGF0cy5IaXRzLCAxKQoJaWYgcy5zdGF0c0VuYWJsZWQgewoJCXMuaGFzaG1hcFN0YXRzW2tleV0rKwoJfQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBtaXNzKCkgewoJYXRvbWljLkFkZEludDY0KCZzLnN0YXRzLk1pc3NlcywgMSkKfQoKZnVuYyAocyAqY2FjaGVTaGFyZCkgZGVsaGl0KCkgewoJYXRvbWljLkFkZEludDY0KCZzLnN0YXRzLkRlbEhpdHMsIDEpCn0KCmZ1bmMgKHMgKmNhY2hlU2hhcmQpIGRlbG1pc3MoKSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuRGVsTWlzc2VzLCAxKQp9CgpmdW5jIChzICpjYWNoZVNoYXJkKSBjb2xsaXNpb24oKSB7CglhdG9taWMuQWRkSW50NjQoJnMuc3RhdHMuQ29sbGlzaW9ucywgMSkKfQoKZnVuYyBpbml0TmV3U2hhcmQoY29uZmlnIENvbmZpZywgY2FsbGJhY2sgb25SZW1vdmVDYWxsYmFjaywgY2xvY2sgY2xvY2spICpjYWNoZVNoYXJkIHsKCWJ5dGVzUXVldWVJbml0aWFsQ2FwYWNpdHkgOj0gY29uZmlnLmluaXRpYWxTaGFyZFNpemUoKSAqIGNvbmZpZy5NYXhFbnRyeVNpemUKCW1heGltdW1TaGFyZFNpemVJbkJ5dGVzIDo9IGNvbmZpZy5tYXhpbXVtU2hhcmRTaXplSW5CeXRlcygpCglpZiBtYXhpbXVtU2hhcmRTaXplSW5CeXRlcyA+IDAgJiYgYnl0ZXNRdWV1ZUluaXRpYWxDYXBhY2l0eSA+IG1heGltdW1TaGFyZFNpemVJbkJ5dGVzIHsKCQlieXRlc1F1ZXVlSW5pdGlhbENhcGFjaXR5ID0gbWF4aW11bVNoYXJkU2l6ZUluQnl0ZXMKCX0KCXJldHVybiAmY2FjaGVTaGFyZHsKCQloYXNobWFwOiAgICAgIG1ha2UobWFwW3VpbnQ2NF11aW50NjQsIGNvbmZpZy5pbml0aWFsU2hhcmRTaXplKCkpLAoJCWhhc2htYXBTdGF0czogbWFrZShtYXBbdWludDY0XXVpbnQzMiwgY29uZmlnLmluaXRpYWxTaGFyZFNpemUoKSksCgkJZW50cmllczogICAgICAqcXVldWUuTmV3Qnl0ZXNRdWV1ZShieXRlc1F1ZXVlSW5pdGlhbENhcGFjaXR5LCBtYXhpbXVtU2hhcmRTaXplSW5CeXRlcywgY29uZmlnLlZlcmJvc2UpLAoJCWVudHJ5QnVmZmVyOiAgbWFrZShbXWJ5dGUsIGNvbmZpZy5NYXhFbnRyeVNpemUraGVhZGVyc1NpemVJbkJ5dGVzKSwKCQlvblJlbW92ZTogICAgIGNhbGxiYWNrLAoKCQlpc1ZlcmJvc2U6ICAgIGNvbmZpZy5WZXJib3NlLAoJCWxvZ2dlcjogICAgICAgbmV3TG9nZ2VyKGNvbmZpZy5Mb2dnZXIpLAoJCWNsb2NrOiAgICAgICAgY2xvY2ssCgkJbGlmZVdpbmRvdzogICB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKSwKCQlzdGF0c0VuYWJsZWQ6IGNvbmZpZy5TdGF0c0VuYWJsZWQsCgkJY2xlYW5FbmFibGVkOiBjb25maWcuQ2xlYW5XaW5kb3cgPiAwLAoJfQp9Cg==", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..68da1a82d4dc6f81fbf6180c025eb248b464d5b1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:00548af95e16e124e94ef26000130c0d7fa4b1b3fa5cc964f54da2508e8553dc" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..51eb537072eeef99211c967c5b85d0934b6a7209 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/manifest.json @@ -0,0 +1,561 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheInitialCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveWithReasonCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNilValueCaching" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotFound" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorInInvalidState" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEvictionShouldEvictOnlyFromUpdatedShard" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithMostShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEviction" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_allocateAdditionalMemoryLeadPanic" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfoCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithAllShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotPresent" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithConcurrentUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Before_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/After_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheRestStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIterator" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/Shards_number_must_be_power_of_two" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntriesInWindow_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntrySize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/HardMaxCacheSize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestConstructCacheWithDefaultHasher" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestHashCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestGetOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveEntriesWhenShardIsFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryBiggerThanMaxShardSizeError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRetrievingEntryShouldCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveGetEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOldestEntryDeletionWhenMaxCacheSizeIsReached" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestIterateOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDel" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndReadParallelSameKeyWithStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDelRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCleanShouldEvictAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestParallelSetAndIteration" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example_custom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..5b3717cf95d37288c1216fa69a83a42d8f582e97 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__m757p3t9/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "db55a9c1c92454ec462f21dbf72d47f7b85eb2126d2ae7c276a3f397b9f7b3a4", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/release-drafter.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/release-drafter.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b50bccd0288a6b533fc93159143a83bbe5567e6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.github/release-drafter.yml @@ -0,0 +1,19 @@ +name-template: "v$NEXT_PATCH_VERSION 🌈" +tag-template: "v$NEXT_PATCH_VERSION" +categories: + - title: "🚀 Features" + labels: + - "feature" + - "enhancement" + - title: "🐛 Bug Fixes" + labels: + - "fix" + - "bugfix" + - "bug" + - title: "🧰 Maintenance" + label: "chore" +change-template: "- $TITLE @$AUTHOR (#$NUMBER)" +template: | + ## Changes + + $CHANGES diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.gitignore b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..78869152118bdc8b125a783a699a9d202550b296 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.gitignore @@ -0,0 +1,11 @@ +.idea +.DS_Store +/server/server.exe +/server/server +/server/server_dar* +/server/server_fre* +/server/server_win* +/server/server_net* +/server/server_ope* +/server/server_lin* +CHANGELOG.md diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.golangci.yaml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.golangci.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b96185f81ea59a0f1eee3376bbfc14c4f58f3d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/.golangci.yaml @@ -0,0 +1,27 @@ +version: "2" +linters: + disable: + - errcheck + settings: + staticcheck: + checks: + - -SA1019 + - all + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/LICENSE b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..8dada3edaf50dbc082c9a125058f25def75e625a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..badf71a150b35e9abe34c099a783a99e7af4f8fe --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/README.md @@ -0,0 +1,204 @@ +# BigCache [![Build Status](https://github.com/allegro/bigcache/workflows/build/badge.svg)](https://github.com/allegro/bigcache/actions?query=workflow%3Abuild) [![Coverage Status](https://coveralls.io/repos/github/allegro/bigcache/badge.svg?branch=main)](https://coveralls.io/github/allegro/bigcache?branch=main) [![GoDoc](https://godoc.org/github.com/allegro/bigcache/v3?status.svg)](https://godoc.org/github.com/allegro/bigcache/v3) [![Go Report Card](https://goreportcard.com/badge/github.com/allegro/bigcache/v3)](https://goreportcard.com/report/github.com/allegro/bigcache/v3) + +Fast, concurrent, evicting in-memory cache written to keep big number of entries without impact on performance. +BigCache keeps entries on heap but omits GC for them. To achieve that, operations on byte slices take place, +therefore entries (de)serialization in front of the cache will be needed in most use cases. + +Requires Go 1.12 or newer. + +## Usage + +### Simple initialization + +```go +import ( + "fmt" + "context" + "github.com/allegro/bigcache/v3" +) + +cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10 * time.Minute)) + +cache.Set("my-unique-key", []byte("value")) + +entry, _ := cache.Get("my-unique-key") +fmt.Println(string(entry)) +``` + +### Custom initialization + +When cache load can be predicted in advance then it is better to use custom initialization because additional memory +allocation can be avoided in that way. + +```go +import ( + "log" + + "github.com/allegro/bigcache/v3" +) + +config := bigcache.Config { + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + +cache, initErr := bigcache.New(context.Background(), config) +if initErr != nil { + log.Fatal(initErr) +} + +cache.Set("my-unique-key", []byte("value")) + +if entry, err := cache.Get("my-unique-key"); err == nil { + fmt.Println(string(entry)) +} +``` + +### `LifeWindow` & `CleanWindow` + +1. `LifeWindow` is a time. After that time, an entry can be called dead but not deleted. + +2. `CleanWindow` is a time. After that time, all the dead entries will be deleted, but not the entries that still have life. + +## [Benchmarks](https://github.com/allegro/bigcache-bench) + +Three caches were compared: bigcache, [freecache](https://github.com/coocood/freecache) and map. +Benchmark tests were made using an +i7-6700K CPU @ 4.00GHz with 32GB of RAM on Ubuntu 18.04 LTS (5.2.12-050212-generic). + +Benchmarks source code can be found [here](https://github.com/allegro/bigcache-bench) + +### Writes and reads + +```bash +go version +go version go1.13 linux/amd64 + +go test -bench=. -benchmem -benchtime=4s ./... -timeout 30m +goos: linux +goarch: amd64 +pkg: github.com/allegro/bigcache/v3/caches_bench +BenchmarkMapSet-8 12999889 376 ns/op 199 B/op 3 allocs/op +BenchmarkConcurrentMapSet-8 4355726 1275 ns/op 337 B/op 8 allocs/op +BenchmarkFreeCacheSet-8 11068976 703 ns/op 328 B/op 2 allocs/op +BenchmarkBigCacheSet-8 10183717 478 ns/op 304 B/op 2 allocs/op +BenchmarkMapGet-8 16536015 324 ns/op 23 B/op 1 allocs/op +BenchmarkConcurrentMapGet-8 13165708 401 ns/op 24 B/op 2 allocs/op +BenchmarkFreeCacheGet-8 10137682 690 ns/op 136 B/op 2 allocs/op +BenchmarkBigCacheGet-8 11423854 450 ns/op 152 B/op 4 allocs/op +BenchmarkBigCacheSetParallel-8 34233472 148 ns/op 317 B/op 3 allocs/op +BenchmarkFreeCacheSetParallel-8 34222654 268 ns/op 350 B/op 3 allocs/op +BenchmarkConcurrentMapSetParallel-8 19635688 240 ns/op 200 B/op 6 allocs/op +BenchmarkBigCacheGetParallel-8 60547064 86.1 ns/op 152 B/op 4 allocs/op +BenchmarkFreeCacheGetParallel-8 50701280 147 ns/op 136 B/op 3 allocs/op +BenchmarkConcurrentMapGetParallel-8 27353288 175 ns/op 24 B/op 2 allocs/op +PASS +ok github.com/allegro/bigcache/v3/caches_bench 256.257s +``` + +Writes and reads in bigcache are faster than in freecache. +Writes to map are the slowest. + +### GC pause time + +```bash +go version +go version go1.13 linux/amd64 + +go run caches_gc_overhead_comparison.go + +Number of entries: 20000000 +GC pause for bigcache: 1.506077ms +GC pause for freecache: 5.594416ms +GC pause for map: 9.347015ms +``` + +``` +go version +go version go1.13 linux/arm64 + +go run caches_gc_overhead_comparison.go +Number of entries: 20000000 +GC pause for bigcache: 22.382827ms +GC pause for freecache: 41.264651ms +GC pause for map: 72.236853ms +``` + +Test shows how long are the GC pauses for caches filled with 20mln of entries. +Bigcache and freecache have very similar GC pause time. + +### Memory usage + +You may encounter system memory reporting what appears to be an exponential increase, however this is expected behaviour. Go runtime allocates memory in chunks or 'spans' and will inform the OS when they are no longer required by changing their state to 'idle'. The 'spans' will remain part of the process resource usage until the OS needs to repurpose the address. Further reading available [here](https://utcc.utoronto.ca/~cks/space/blog/programming/GoNoMemoryFreeing). + +## How it works + +BigCache relies on optimization presented in 1.5 version of Go ([issue-9477](https://github.com/golang/go/issues/9477)). +This optimization states that if map without pointers in keys and values is used then GC will omit its content. +Therefore BigCache uses `map[uint64]uint32` where keys are hashed and values are offsets of entries. + +Entries are kept in byte slices, to omit GC again. +Byte slices size can grow to gigabytes without impact on performance +because GC will only see single pointer to it. + +### Collisions + +BigCache does not handle collisions. When new item is inserted and it's hash collides with previously stored item, new item overwrites previously stored value. + +## Bigcache vs Freecache + +Both caches provide the same core features but they reduce GC overhead in different ways. +Bigcache relies on `map[uint64]uint32`, freecache implements its own mapping built on +slices to reduce number of pointers. + +Results from benchmark tests are presented above. +One of the advantage of bigcache over freecache is that you don’t need to know +the size of the cache in advance, because when bigcache is full, +it can allocate additional memory for new entries instead of +overwriting existing ones as freecache does currently. +However hard max size in bigcache also can be set, check [HardMaxCacheSize](https://godoc.org/github.com/allegro/bigcache#Config). + +## HTTP Server + +This package also includes an easily deployable HTTP implementation of BigCache, which can be found in the [server](/server) package. + +## More + +Bigcache genesis is described in allegro.tech blog post: [writing a very fast cache service in Go](http://allegro.tech/2016/03/writing-fast-cache-service-in-go.html) + +## License + +BigCache is released under the Apache 2.0 license (see [LICENSE](LICENSE)) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bigcache.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bigcache.go new file mode 100644 index 0000000000000000000000000000000000000000..af18d09f23e757a27ac09fa87bb6f792386d9ae4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bigcache.go @@ -0,0 +1,274 @@ +package bigcache + +import ( + "context" + "errors" + "time" +) + +const ( + minimumEntriesInShard = 10 // Minimum number of entries in single shard +) + +// BigCache is fast, concurrent, evicting cache created to keep big number of entries without impact on performance. +// It keeps entries on heap but omits GC for them. To achieve that, operations take place on byte arrays, +// therefore entries (de)serialization in front of the cache will be needed in most use cases. +type BigCache struct { + shards []*cacheShard + lifeWindow uint64 + clock clock + hash Hasher + config Config + shardMask uint64 + close chan struct{} +} + +// Response will contain metadata about the entry for which GetWithInfo(key) was called +type Response struct { + EntryStatus RemoveReason +} + +// RemoveReason is a value used to signal to the user why a particular key was removed in the OnRemove callback. +type RemoveReason uint32 + +const ( + // Expired means the key is past its LifeWindow. + Expired = RemoveReason(1) + // NoSpace means the key is the oldest and the cache size was at its maximum when Set was called, or the + // entry exceeded the maximum shard size. + NoSpace = RemoveReason(2) + // Deleted means Delete was called and this key was removed as a result. + Deleted = RemoveReason(3) +) + +// New initialize new instance of BigCache +func New(ctx context.Context, config Config) (*BigCache, error) { + return newBigCache(ctx, config, &systemClock{}) +} + +// NewBigCache initialize new instance of BigCache +// +// Deprecated: NewBigCache is deprecated, please use New(ctx, config) instead, +// New takes in context and can gracefully +// shutdown with context cancellations +func NewBigCache(config Config) (*BigCache, error) { + return newBigCache(context.Background(), config, &systemClock{}) +} + +func newBigCache(ctx context.Context, config Config, clock clock) (*BigCache, error) { + if !isPowerOfTwo(config.Shards) { + return nil, errors.New("Shards number must be power of two") + } + if config.MaxEntrySize < 0 { + return nil, errors.New("MaxEntrySize must be >= 0") + } + if config.MaxEntriesInWindow < 0 { + return nil, errors.New("MaxEntriesInWindow must be >= 0") + } + if config.HardMaxCacheSize < 0 { + return nil, errors.New("HardMaxCacheSize must be >= 0") + } + + lifeWindowSeconds := uint64(config.LifeWindow.Seconds()) + if config.CleanWindow > 0 && lifeWindowSeconds == 0 { + return nil, errors.New("LifeWindow must be >= 1s when CleanWindow is set") + } + + if config.Hasher == nil { + config.Hasher = newDefaultHasher() + } + + cache := &BigCache{ + shards: make([]*cacheShard, config.Shards), + lifeWindow: lifeWindowSeconds, + clock: clock, + hash: config.Hasher, + config: config, + shardMask: uint64(config.Shards - 1), + close: make(chan struct{}), + } + + var onRemove func(wrappedEntry []byte, reason RemoveReason) + if config.OnRemoveWithMetadata != nil { + onRemove = cache.providedOnRemoveWithMetadata + } else if config.OnRemove != nil { + onRemove = cache.providedOnRemove + } else if config.OnRemoveWithReason != nil { + onRemove = cache.providedOnRemoveWithReason + } else { + onRemove = cache.notProvidedOnRemove + } + + for i := 0; i < config.Shards; i++ { + cache.shards[i] = initNewShard(config, onRemove, clock) + } + + if config.CleanWindow > 0 { + go func() { + ticker := time.NewTicker(config.CleanWindow) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case t := <-ticker.C: + cache.cleanUp(uint64(t.Unix())) + case <-cache.close: + return + } + } + }() + } + + return cache, nil +} + +// Close is used to signal a shutdown of the cache when you are done with it. +// This allows the cleaning goroutines to exit and ensures references are not +// kept to the cache preventing GC of the entire cache. +func (c *BigCache) Close() error { + close(c.close) + return nil +} + +// Get reads entry for the key. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) Get(key string) ([]byte, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.get(key, hashedKey) +} + +// GetWithInfo reads entry for the key with Response info. +// It returns an ErrEntryNotFound when +// no entry exists for the given key. +func (c *BigCache) GetWithInfo(key string) ([]byte, Response, error) { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getWithInfo(key, hashedKey) +} + +// Set saves entry under the key +func (c *BigCache) Set(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.set(key, hashedKey, entry) +} + +// Append appends entry under the key if key exists, otherwise +// it will set the key (same behaviour as Set()). With Append() you can +// concatenate multiple entries under the same key in a lock-optimized way. +func (c *BigCache) Append(key string, entry []byte) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.append(key, hashedKey, entry) +} + +// Delete removes the key +func (c *BigCache) Delete(key string) error { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.del(hashedKey) +} + +// Reset empties all cache shards +func (c *BigCache) Reset() error { + for _, shard := range c.shards { + shard.reset(c.config) + } + return nil +} + +// ResetStats resets cache stats +func (c *BigCache) ResetStats() error { + for _, shard := range c.shards { + shard.resetStats() + } + return nil +} + +// Len computes the number of entries in the cache. +func (c *BigCache) Len() int { + var len int + for _, shard := range c.shards { + len += shard.len() + } + return len +} + +// Capacity returns the amount of bytes stored in the cache. +func (c *BigCache) Capacity() int { + var len int + for _, shard := range c.shards { + len += shard.capacity() + } + return len +} + +// Stats returns cache's statistics +func (c *BigCache) Stats() Stats { + var s Stats + for _, shard := range c.shards { + tmp := shard.getStats() + s.Hits += tmp.Hits + s.Misses += tmp.Misses + s.DelHits += tmp.DelHits + s.DelMisses += tmp.DelMisses + s.Collisions += tmp.Collisions + } + return s +} + +// KeyMetadata returns number of times a cached resource was requested. +func (c *BigCache) KeyMetadata(key string) Metadata { + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + return shard.getKeyMetadataWithLock(hashedKey) +} + +// Iterator returns iterator function to iterate over EntryInfo's from whole cache. +func (c *BigCache) Iterator() *EntryInfoIterator { + return newIterator(c) +} + +func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp < oldestTimestamp { + return false + } + if currentTimestamp-oldestTimestamp > c.lifeWindow { + evict(Expired) + return true + } + return false +} + +func (c *BigCache) cleanUp(currentTimestamp uint64) { + for _, shard := range c.shards { + shard.cleanUp(currentTimestamp) + } +} + +func (c *BigCache) getShard(hashedKey uint64) (shard *cacheShard) { + return c.shards[hashedKey&c.shardMask] +} + +func (c *BigCache) providedOnRemove(wrappedEntry []byte, reason RemoveReason) { + c.config.OnRemove(readKeyFromEntry(wrappedEntry), readEntry(wrappedEntry)) +} + +func (c *BigCache) providedOnRemoveWithReason(wrappedEntry []byte, reason RemoveReason) { + +} + +func (c *BigCache) notProvidedOnRemove(wrappedEntry []byte, reason RemoveReason) { +} + +func (c *BigCache) providedOnRemoveWithMetadata(wrappedEntry []byte, reason RemoveReason) { + key := readKeyFromEntry(wrappedEntry) + + hashedKey := c.hash.Sum64(key) + shard := c.getShard(hashedKey) + c.config.OnRemoveWithMetadata(key, readEntry(wrappedEntry), shard.getKeyMetadata(hashedKey)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bytes.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bytes.go new file mode 100644 index 0000000000000000000000000000000000000000..e0743b0c173862f7f80ee4ef88b34c9aea71e43f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bytes.go @@ -0,0 +1,12 @@ +//go:build !appengine +// +build !appengine + +package bigcache + +import ( + "unsafe" +) + +func bytesToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bytes_appengine.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bytes_appengine.go new file mode 100644 index 0000000000000000000000000000000000000000..4fd039d9c1270689893df81d362b1c35895a89b6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/bytes_appengine.go @@ -0,0 +1,8 @@ +//go:build appengine +// +build appengine + +package bigcache + +func bytesToString(b []byte) string { + return string(b) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/clock.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/clock.go new file mode 100644 index 0000000000000000000000000000000000000000..195d01af8b66eb96cf65d9a45d7e1fa1e5d6e348 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/clock.go @@ -0,0 +1,14 @@ +package bigcache + +import "time" + +type clock interface { + Epoch() int64 +} + +type systemClock struct { +} + +func (c systemClock) Epoch() int64 { + return time.Now().Unix() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/config.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/config.go new file mode 100644 index 0000000000000000000000000000000000000000..63a4e9b117cce58588d9fc5d2f3fc9a52348d55b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/config.go @@ -0,0 +1,97 @@ +package bigcache + +import "time" + +// Config for BigCache +type Config struct { + // Number of cache shards, value must be a power of two + Shards int + // Time after which entry can be evicted + LifeWindow time.Duration + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow time.Duration + // Max number of entries in life window. Used only to calculate initial size for cache shards. + // When proper value is set then additional memory allocation does not occur. + MaxEntriesInWindow int + // Max size of entry in bytes. Used only to calculate initial size for cache shards. + MaxEntrySize int + // StatsEnabled if true calculate the number of times a cached resource was requested. + StatsEnabled bool + // Verbose mode prints information about new memory allocation + Verbose bool + // Hasher used to map between string keys and unsigned 64bit integers, by default fnv64 hashing is used. + Hasher Hasher + // HardMaxCacheSize is a limit for BytesQueue size in MB. + // It can protect application from consuming all available memory on machine, therefore from running OOM Killer. + // Default value is 0 which means unlimited size. When the limit is higher than 0 and reached then + // the oldest entries are overridden for the new ones. The max memory consumption will be bigger than + // HardMaxCacheSize due to Shards' s additional memory. Every Shard consumes additional memory for map of keys + // and statistics (map[uint64]uint32) the size of this map is equal to number of entries in + // cache ~ 2×(64+32)×n bits + overhead or map itself. + HardMaxCacheSize int + // OnRemove is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // ignored if OnRemoveWithMetadata is specified. + OnRemove func(key string, entry []byte) + // OnRemoveWithMetadata is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A structure representing details about that specific entry. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemoveWithMetadata func(key string, entry []byte, keyMetadata Metadata) + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason func(key string, entry []byte, reason RemoveReason) + + onRemoveFilter int + + // Logger is a logging interface and used in combination with `Verbose` + // Defaults to `DefaultLogger()` + Logger Logger +} + +// DefaultConfig initializes config with default values. +// When load for BigCache can be predicted in advance then it is better to use custom config. +func DefaultConfig(eviction time.Duration) Config { + return Config{ + Shards: 1024, + LifeWindow: eviction, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: false, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 0, + Logger: DefaultLogger(), + } +} + +// initialShardSize computes initial shard size +func (c Config) initialShardSize() int { + return max(c.MaxEntriesInWindow/c.Shards, minimumEntriesInShard) +} + +// maximumShardSizeInBytes computes maximum shard size in bytes +func (c Config) maximumShardSizeInBytes() int { + maxShardSize := 0 + + if c.HardMaxCacheSize > 0 { + maxShardSize = convertMBToBytes(c.HardMaxCacheSize) / c.Shards + } + + return maxShardSize +} + +// OnRemoveFilterSet sets which remove reasons will trigger a call to OnRemoveWithReason. +// Filtering out reasons prevents bigcache from unwrapping them, which saves cpu. +func (c Config) OnRemoveFilterSet(reasons ...RemoveReason) Config { + c.onRemoveFilter = 0 + for i := range reasons { + c.onRemoveFilter |= 1 << uint(reasons[i]) + } + + return c +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/encoding.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/encoding.go new file mode 100644 index 0000000000000000000000000000000000000000..8d231ae8bea1f30161f7900aa277b64d99b6e2c3 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/encoding.go @@ -0,0 +1,83 @@ +package bigcache + +import ( + "encoding/binary" +) + +const ( + timestampSizeInBytes = 8 // Number of bytes used for timestamp + hashSizeInBytes = 8 // Number of bytes used for hash + keySizeInBytes = 2 // Number of bytes used for size of entry key + headersSizeInBytes = timestampSizeInBytes + hashSizeInBytes + keySizeInBytes // Number of bytes used for all headers +) + +func wrapEntry(timestamp uint64, hash uint64, key string, entry []byte, buffer *[]byte) []byte { + keyLength := len(key) + blobLength := len(entry) + headersSizeInBytes + keyLength + + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + binary.LittleEndian.PutUint64(blob[timestampSizeInBytes:], hash) + binary.LittleEndian.PutUint16(blob[timestampSizeInBytes+hashSizeInBytes:], uint16(keyLength)) + copy(blob[headersSizeInBytes:], key) + copy(blob[headersSizeInBytes+keyLength:], entry) + + return blob[:blobLength] +} + +func appendToWrappedEntry(timestamp uint64, wrappedEntry []byte, entry []byte, buffer *[]byte) []byte { + blobLength := len(wrappedEntry) + len(entry) + if blobLength > len(*buffer) { + *buffer = make([]byte, blobLength) + } + + blob := *buffer + + binary.LittleEndian.PutUint64(blob, timestamp) + copy(blob[timestampSizeInBytes:], wrappedEntry[timestampSizeInBytes:]) + copy(blob[len(wrappedEntry):], entry) + + return blob[:blobLength] +} + +func readEntry(data []byte) []byte { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, len(data)-int(headersSizeInBytes+length)) + copy(dst, data[headersSizeInBytes+length:]) + + return dst +} + +func readTimestampFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data) +} + +func readKeyFromEntry(data []byte) string { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + // copy on read + dst := make([]byte, length) + copy(dst, data[headersSizeInBytes:headersSizeInBytes+length]) + + return bytesToString(dst) +} + +func compareKeyFromEntry(data []byte, key string) bool { + length := binary.LittleEndian.Uint16(data[timestampSizeInBytes+hashSizeInBytes:]) + + return bytesToString(data[headersSizeInBytes:headersSizeInBytes+length]) == key +} + +func readHashFromEntry(data []byte) uint64 { + return binary.LittleEndian.Uint64(data[timestampSizeInBytes:]) +} + +func resetHashFromEntry(data []byte) { + binary.LittleEndian.PutUint64(data[timestampSizeInBytes:], 0) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/entry_not_found_error.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/entry_not_found_error.go new file mode 100644 index 0000000000000000000000000000000000000000..8993384d84319f3b517f99fb69874a586a21cfe8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/entry_not_found_error.go @@ -0,0 +1,8 @@ +package bigcache + +import "errors" + +var ( + // ErrEntryNotFound is an error type struct which is returned when entry was not found for provided key + ErrEntryNotFound = errors.New("Entry not found") +) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/fnv.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/fnv.go new file mode 100644 index 0000000000000000000000000000000000000000..188c9aa6dcbd297be6ac46418158a686e2638c88 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/fnv.go @@ -0,0 +1,28 @@ +package bigcache + +// newDefaultHasher returns a new 64-bit FNV-1a Hasher which makes no memory allocations. +// Its Sum64 method will lay the value out in big-endian byte order. +// See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function +func newDefaultHasher() Hasher { + return fnv64a{} +} + +type fnv64a struct{} + +const ( + // offset64 FNVa offset basis. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + offset64 = 14695981039346656037 + // prime64 FNVa prime value. See https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function#FNV-1a_hash + prime64 = 1099511628211 +) + +// Sum64 gets the string and returns its uint64 hash value. +func (f fnv64a) Sum64(key string) uint64 { + var hash uint64 = offset64 + for i := 0; i < len(key); i++ { + hash ^= uint64(key[i]) + hash *= prime64 + } + + return hash +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/go.mod b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/go.mod new file mode 100644 index 0000000000000000000000000000000000000000..1eea1f42ec2eee46210f9b384bbaa3eaf7d8eb93 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/go.mod @@ -0,0 +1,3 @@ +module github.com/allegro/bigcache/v3 + +go 1.16 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/go.sum b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/go.sum new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/hash.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/hash.go new file mode 100644 index 0000000000000000000000000000000000000000..5f8ade774daae7fa5beade0c01ecf14e895dfcc4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/hash.go @@ -0,0 +1,8 @@ +package bigcache + +// Hasher is responsible for generating unsigned, 64 bit hash of provided string. Hasher should minimize collisions +// (generating same hash for different strings) and while performance is also important fast functions are preferable (i.e. +// you can use FarmHash family). +type Hasher interface { + Sum64(string) uint64 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/iterator.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/iterator.go new file mode 100644 index 0000000000000000000000000000000000000000..db2a2ef4b61220c1bf821751353e18f548ca0cde --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/iterator.go @@ -0,0 +1,146 @@ +package bigcache + +import ( + "sync" +) + +type iteratorError string + +func (e iteratorError) Error() string { + return string(e) +} + +// ErrInvalidIteratorState is reported when iterator is in invalid state +const ErrInvalidIteratorState = iteratorError("Iterator is in invalid state. Use SetNext() to move to next position") + +// ErrCannotRetrieveEntry is reported when entry cannot be retrieved from underlying +const ErrCannotRetrieveEntry = iteratorError("Could not retrieve entry from cache") + +var emptyEntryInfo = EntryInfo{} + +// EntryInfo holds informations about entry in the cache +type EntryInfo struct { + timestamp uint64 + hash uint64 + key string + value []byte + err error +} + +// Key returns entry's underlying key +func (e EntryInfo) Key() string { + return e.key +} + +// Hash returns entry's hash value +func (e EntryInfo) Hash() uint64 { + return e.hash +} + +// Timestamp returns entry's timestamp (time of insertion) +func (e EntryInfo) Timestamp() uint64 { + return e.timestamp +} + +// Value returns entry's underlying value +func (e EntryInfo) Value() []byte { + return e.value +} + +// EntryInfoIterator allows to iterate over entries in the cache +type EntryInfoIterator struct { + mutex sync.Mutex + cache *BigCache + currentShard int + currentIndex int + currentEntryInfo EntryInfo + elements []uint64 + elementsCount int + valid bool +} + +// SetNext moves to next element and returns true if it exists. +func (it *EntryInfoIterator) SetNext() bool { + it.mutex.Lock() + + it.valid = false + it.currentIndex++ + + if it.elementsCount > it.currentIndex { + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + + for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { + it.elements, it.elementsCount = it.cache.shards[i].copyHashedKeys() + + // Non empty shard - stick with it + if it.elementsCount > 0 { + it.currentIndex = 0 + it.currentShard = i + it.valid = true + + empty := it.setCurrentEntry() + it.mutex.Unlock() + + if empty { + return it.SetNext() + } + return true + } + } + it.mutex.Unlock() + return false +} + +func (it *EntryInfoIterator) setCurrentEntry() bool { + var entryNotFound = false + entry, err := it.cache.shards[it.currentShard].getEntry(it.elements[it.currentIndex]) + + if err == ErrEntryNotFound { + it.currentEntryInfo = emptyEntryInfo + entryNotFound = true + } else if err != nil { + it.currentEntryInfo = EntryInfo{ + err: err, + } + } else { + it.currentEntryInfo = EntryInfo{ + timestamp: readTimestampFromEntry(entry), + hash: readHashFromEntry(entry), + key: readKeyFromEntry(entry), + value: readEntry(entry), + err: err, + } + } + + return entryNotFound +} + +func newIterator(cache *BigCache) *EntryInfoIterator { + elements, count := cache.shards[0].copyHashedKeys() + + return &EntryInfoIterator{ + cache: cache, + currentShard: 0, + currentIndex: -1, + elements: elements, + elementsCount: count, + } +} + +// Value returns current value from the iterator +func (it *EntryInfoIterator) Value() (EntryInfo, error) { + if !it.valid { + return emptyEntryInfo, ErrInvalidIteratorState + } + + return it.currentEntryInfo, it.currentEntryInfo.err +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/logger.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/logger.go new file mode 100644 index 0000000000000000000000000000000000000000..50e84abc80069ce5e9560bc9ba1cb1b204d3d22e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/logger.go @@ -0,0 +1,30 @@ +package bigcache + +import ( + "log" + "os" +) + +// Logger is invoked when `Config.Verbose=true` +type Logger interface { + Printf(format string, v ...interface{}) +} + +// this is a safeguard, breaking on compile time in case +// `log.Logger` does not adhere to our `Logger` interface. +// see https://golang.org/doc/faq#guarantee_satisfies_interface +var _ Logger = &log.Logger{} + +// DefaultLogger returns a `Logger` implementation +// backed by stdlib's log +func DefaultLogger() *log.Logger { + return log.New(os.Stdout, "", log.LstdFlags) +} + +func newLogger(custom Logger) Logger { + if custom != nil { + return custom + } + + return DefaultLogger() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/queue/bytes_queue.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/queue/bytes_queue.go new file mode 100644 index 0000000000000000000000000000000000000000..c4fe2c088e1eb0c168fadcd720c428c844ae9d71 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/queue/bytes_queue.go @@ -0,0 +1,269 @@ +package queue + +import ( + "encoding/binary" + "log" + "time" +) + +const ( + // Number of bytes to encode 0 in uvarint format + minimumHeaderSize = 17 // 1 byte blobsize + timestampSizeInBytes + hashSizeInBytes + // Bytes before left margin are not used. Zero index means element does not exist in queue, useful while reading slice from index + leftMarginIndex = 1 +) + +var ( + errEmptyQueue = &queueError{"Empty queue"} + errInvalidIndex = &queueError{"Index must be greater than zero. Invalid index."} + errIndexOutOfBounds = &queueError{"Index out of range"} +) + +// BytesQueue is a non-thread safe queue type of fifo based on bytes array. +// For every push operation index of entry is returned. It can be used to read the entry later +type BytesQueue struct { + full bool + array []byte + capacity int + maxCapacity int + head int + tail int + count int + rightMargin int + headerBuffer []byte + verbose bool +} + +type queueError struct { + message string +} + +// getNeededSize returns the number of bytes an entry of length need in the queue +func getNeededSize(length int) int { + var header int + switch { + case length < 127: // 1<<7-1 + header = 1 + case length < 16382: // 1<<14-2 + header = 2 + case length < 2097149: // 1<<21 -3 + header = 3 + case length < 268435452: // 1<<28 -4 + header = 4 + default: + header = 5 + } + + return length + header +} + +// NewBytesQueue initialize new bytes queue. +// capacity is used in bytes array allocation +// When verbose flag is set then information about memory allocation are printed +func NewBytesQueue(capacity int, maxCapacity int, verbose bool) *BytesQueue { + return &BytesQueue{ + array: make([]byte, capacity), + capacity: capacity, + maxCapacity: maxCapacity, + headerBuffer: make([]byte, binary.MaxVarintLen32), + tail: leftMarginIndex, + head: leftMarginIndex, + rightMargin: leftMarginIndex, + verbose: verbose, + } +} + +// Reset removes all entries from queue +func (q *BytesQueue) Reset() { + // Just reset indexes + q.tail = leftMarginIndex + q.head = leftMarginIndex + q.rightMargin = leftMarginIndex + q.count = 0 + q.full = false +} + +// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. +// Returns index for pushed data or error if maximum size queue limit is reached. +func (q *BytesQueue) Push(data []byte) (int, error) { + neededSize := getNeededSize(len(data)) + + if !q.canInsertAfterTail(neededSize) { + if q.canInsertBeforeHead(neededSize) { + q.tail = leftMarginIndex + } else if q.capacity+neededSize >= q.maxCapacity && q.maxCapacity > 0 { + return -1, &queueError{"Full queue. Maximum size limit reached."} + } else { + q.allocateAdditionalMemory(neededSize) + } + } + + index := q.tail + + q.push(data, neededSize) + + return index, nil +} + +func (q *BytesQueue) allocateAdditionalMemory(minimum int) { + start := time.Now() + if q.capacity < minimum { + q.capacity += minimum + } + q.capacity = q.capacity * 2 + if q.capacity > q.maxCapacity && q.maxCapacity > 0 { + q.capacity = q.maxCapacity + } + + oldArray := q.array + q.array = make([]byte, q.capacity) + + if leftMarginIndex != q.rightMargin { + copy(q.array, oldArray[:q.rightMargin]) + + if q.tail <= q.head { + if q.tail != q.head { + // created slice is slightly larger than need but this is fine after only the needed bytes are copied + q.push(make([]byte, q.head-q.tail), q.head-q.tail) + } + + q.head = leftMarginIndex + q.tail = q.rightMargin + } + } + + q.full = false + + if q.verbose { + log.Printf("Allocated new queue in %s; Capacity: %d \n", time.Since(start), q.capacity) + } +} + +func (q *BytesQueue) push(data []byte, len int) { + headerEntrySize := binary.PutUvarint(q.headerBuffer, uint64(len)) + q.copy(q.headerBuffer, headerEntrySize) + + q.copy(data, len-headerEntrySize) + + if q.tail > q.head { + q.rightMargin = q.tail + } + if q.tail == q.head { + q.full = true + } + + q.count++ +} + +func (q *BytesQueue) copy(data []byte, len int) { + q.tail += copy(q.array[q.tail:], data[:len]) +} + +// Pop reads the oldest entry from queue and moves head pointer to the next one +func (q *BytesQueue) Pop() ([]byte, error) { + data, blockSize, err := q.peek(q.head) + if err != nil { + return nil, err + } + + q.head += blockSize + q.count-- + + if q.head == q.rightMargin { + q.head = leftMarginIndex + if q.tail == q.rightMargin { + q.tail = leftMarginIndex + } + q.rightMargin = q.tail + } + + q.full = false + + return data, nil +} + +// Peek reads the oldest entry from list without moving head pointer +func (q *BytesQueue) Peek() ([]byte, error) { + data, _, err := q.peek(q.head) + return data, err +} + +// Get reads entry from index +func (q *BytesQueue) Get(index int) ([]byte, error) { + data, _, err := q.peek(index) + return data, err +} + +// CheckGet checks if an entry can be read from index +func (q *BytesQueue) CheckGet(index int) error { + return q.peekCheckErr(index) +} + +// Capacity returns number of allocated bytes for queue +func (q *BytesQueue) Capacity() int { + return q.capacity +} + +// Len returns number of entries kept in queue +func (q *BytesQueue) Len() int { + return q.count +} + +// Error returns error message +func (e *queueError) Error() string { + return e.message +} + +// peekCheckErr is identical to peek, but does not actually return any data +func (q *BytesQueue) peekCheckErr(index int) error { + + if q.count == 0 { + return errEmptyQueue + } + + if index <= 0 { + return errInvalidIndex + } + + if index >= len(q.array) { + return errIndexOutOfBounds + } + return nil +} + +// peek returns the data from index and the number of bytes to encode the length of the data in uvarint format +func (q *BytesQueue) peek(index int) ([]byte, int, error) { + err := q.peekCheckErr(index) + if err != nil { + return nil, 0, err + } + + blockSize, n := binary.Uvarint(q.array[index:]) + return q.array[index+n : index+int(blockSize)], int(blockSize), nil +} + +// canInsertAfterTail returns true if it's possible to insert an entry of size of need after the tail of the queue +func (q *BytesQueue) canInsertAfterTail(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.capacity-q.tail >= need + } + // 1. there is exactly need bytes between head and tail, so we do not need + // to reserve extra space for a potential empty entry when realloc this queue + // 2. still have unused space between tail and head, then we must reserve + // at least headerEntrySize bytes so we can put an empty entry + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} + +// canInsertBeforeHead returns true if it's possible to insert an entry of size of need before the head of the queue +func (q *BytesQueue) canInsertBeforeHead(need int) bool { + if q.full { + return false + } + if q.tail >= q.head { + return q.head-leftMarginIndex == need || q.head-leftMarginIndex >= need+minimumHeaderSize + } + return q.head-q.tail == need || q.head-q.tail >= need+minimumHeaderSize +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/README.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/README.md new file mode 100644 index 0000000000000000000000000000000000000000..894235f30e8c62932d36d3b26d7885508fd4dd0c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/README.md @@ -0,0 +1,105 @@ +# BigCache HTTP Server + +This is a basic HTTP server implementation for BigCache. It has a basic RESTful API and is designed for easy operational deployments. This server is intended to be consumed as a standalone executable, for things like Cloud Foundry, Heroku, etc. A design goal is versatility, so if you want to cache pictures, software artifacts, text, or any type of bit, the BigCache HTTP Server should fit your needs. + +```bash +# cache API. +GET /api/v1/cache/{key} +PUT /api/v1/cache/{key} +DELETE /api/v1/cache/{key} + +# stats API. +GET /api/v1/stats +``` + +The cache API is designed for ease-of-use caching and accepts any content type. The stats API will return hit and miss statistics about the cache since the last time the server was started - they will reset whenever the server is restarted. + +### Notes for Operators + +1. No SSL support, currently. +1. No authentication, currently. +1. Stats from the stats API are not persistent. +1. The easiest way to clean the cache is to restart the process; it takes less than a second to initialise. +1. There is no replication or clustering. + +### Command-line Interface + +```powershell +PS C:\go\src\github.com\mxplusb\bigcache\server> .\server.exe -h +Usage of C:\go\src\github.com\mxplusb\bigcache\server\server.exe: + -lifetime duration + Lifetime of each cache object. (default 10m0s) + -logfile string + Location of the logfile. + -max int + Maximum amount of data in the cache in MB. (default 8192) + -maxInWindow int + Used only in initial memory allocation. (default 600000) + -maxShardEntrySize int + The maximum size of each object stored in a shard. Used only in initial memory allocation. (default 500) + -port int + The port to listen on. (default 9090) + -shards int + Number of shards for the cache. (default 1024) + -v Verbose logging. + -version + Print server version. +``` + +Example: + +```bash +$ curl -v -XPUT localhost:9090/api/v1/cache/example -d "yay!" +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> PUT /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> Content-Length: 4 +> Content-Type: application/x-www-form-urlencoded +> +* upload completely sent off: 4 out of 4 bytes +< HTTP/1.1 201 Created +< Date: Fri, 17 Nov 2017 03:50:07 GMT +< Content-Length: 0 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +$ +$ curl -v -XGET localhost:9090/api/v1/cache/example +Note: Unnecessary use of -X or --request, GET is already inferred. +* Trying 127.0.0.1... +* Connected to localhost (127.0.0.1) port 9090 (#0) +> GET /api/v1/cache/example HTTP/1.1 +> Host: localhost:9090 +> User-Agent: curl/7.47.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Date: Fri, 17 Nov 2017 03:50:23 GMT +< Content-Length: 4 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +yay! +``` + +The server does log basic metrics: + +```bash +$ ./server +2017/11/16 22:49:22 cache initialised. +2017/11/16 22:49:22 starting server on :9090 +2017/11/16 22:50:07 stored "example" in cache. +2017/11/16 22:50:07 request took 277000ns. +2017/11/16 22:50:23 request took 9000ns. +``` + +### Acquiring Natively + +This is native Go with no external dependencies, so it will compile for all supported Golang platforms. To build: + +```bash +go build server.go +``` diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/cache_handlers.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/cache_handlers.go new file mode 100644 index 0000000000000000000000000000000000000000..ee802a0df14a7b78fbf25eea54d15697d6d6f620 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/cache_handlers.go @@ -0,0 +1,101 @@ +package main + +import ( + "io" + "log" + "net/http" + "strings" +) + +func cacheIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheHandler(w, r) + case http.MethodPut: + putCacheHandler(w, r) + case http.MethodDelete: + deleteCacheHandler(w, r) + } + }) +} + +func cacheClearHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + clearCache(w, r) + }) +} + +func clearCache(w http.ResponseWriter, r *http.Request) { + if err := cache.Reset(); err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + log.Println("cache is successfully cleared") + w.WriteHeader(http.StatusOK) +} + +// handles get requests. +func getCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't get a key if there is no key.")) + log.Print("empty request.") + return + } + entry, err := cache.Get(target) + if err != nil { + errMsg := (err).Error() + if strings.Contains(errMsg, "not found") { + log.Print(err) + w.WriteHeader(http.StatusNotFound) + return + } + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Write(entry) +} + +func putCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if target == "" { + w.WriteHeader(http.StatusBadRequest) + w.Write([]byte("can't put a key if there is no key.")) + log.Print("empty request.") + return + } + + entry, err := io.ReadAll(r.Body) + if err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + + if err := cache.Set(target, []byte(entry)); err != nil { + log.Print(err) + w.WriteHeader(http.StatusInternalServerError) + return + } + log.Printf("stored \"%s\" in cache.", target) + w.WriteHeader(http.StatusCreated) +} + +// delete cache objects. +func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { + target := r.URL.Path[len(cachePath):] + if err := cache.Delete(target); err != nil { + if strings.Contains((err).Error(), "not found") { + w.WriteHeader(http.StatusNotFound) + log.Printf("%s not found.", target) + return + } + w.WriteHeader(http.StatusInternalServerError) + log.Printf("internal cache error: %s", err) + } + // this is what the RFC says to use when calling DELETE. + w.WriteHeader(http.StatusOK) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/middleware.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/middleware.go new file mode 100644 index 0000000000000000000000000000000000000000..ea963a10c5ecd579d8b0be69395fe3042eef80df --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/middleware.go @@ -0,0 +1,29 @@ +package main + +import ( + "log" + "net/http" + "time" +) + +// our base middleware implementation. +type service func(http.Handler) http.Handler + +// chain load middleware services. +func serviceLoader(h http.Handler, svcs ...service) http.Handler { + for _, svc := range svcs { + h = svc(h) + } + return h +} + +// middleware for request length metrics. +func requestMetrics(l *log.Logger) service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + h.ServeHTTP(w, r) + l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Since(start).Nanoseconds()) + }) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/server.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/server.go new file mode 100644 index 0000000000000000000000000000000000000000..a8f88601efb846ac9c47506baaaffa0bb0afb03e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/server.go @@ -0,0 +1,87 @@ +package main + +import ( + "context" + "flag" + "fmt" + "log" + "net/http" + "os" + "strconv" + + "github.com/allegro/bigcache/v3" +) + +const ( + // base HTTP paths. + apiVersion = "v1" + apiBasePath = "/api/" + apiVersion + "/" + + // path to cache. + cachePath = apiBasePath + "cache/" + statsPath = apiBasePath + "stats" + cacheClearPath = apiBasePath + "cache/clear" + // server version. + version = "1.0.0" +) + +var ( + port int + logfile string + ver bool + + // cache-specific settings. + cache *bigcache.BigCache + config = bigcache.Config{} +) + +func init() { + flag.BoolVar(&config.Verbose, "v", false, "Verbose logging.") + flag.IntVar(&config.Shards, "shards", 1024, "Number of shards for the cache.") + flag.IntVar(&config.MaxEntriesInWindow, "maxInWindow", 1000*10*60, "Used only in initial memory allocation.") + flag.DurationVar(&config.LifeWindow, "lifetime", 100000*100000*60, "Lifetime of each cache object.") + flag.IntVar(&config.HardMaxCacheSize, "max", 8192, "Maximum amount of data in the cache in MB.") + flag.IntVar(&config.MaxEntrySize, "maxShardEntrySize", 500, "The maximum size of each object stored in a shard. Used only in initial memory allocation.") + flag.IntVar(&port, "port", 9090, "The port to listen on.") + flag.StringVar(&logfile, "logfile", "", "Location of the logfile.") + flag.BoolVar(&ver, "version", false, "Print server version.") +} + +func main() { + flag.Parse() + + if ver { + fmt.Printf("BigCache HTTP Server v%s", version) + os.Exit(0) + } + + var logger *log.Logger + + if logfile == "" { + logger = log.New(os.Stdout, "", log.LstdFlags) + } else { + f, err := os.OpenFile(logfile, os.O_APPEND|os.O_WRONLY, 0600) + if err != nil { + panic(err) + } + logger = log.New(f, "", log.LstdFlags) + } + + var err error + cache, err = bigcache.New(context.Background(), config) + if err != nil { + logger.Fatal(err) + } + + logger.Print("cache initialised.") + + // let the middleware log. + http.Handle(cacheClearPath, serviceLoader(cacheClearHandler(), requestMetrics(logger))) + http.Handle(cachePath, serviceLoader(cacheIndexHandler(), requestMetrics(logger))) + http.Handle(statsPath, serviceLoader(statsIndexHandler(), requestMetrics(logger))) + + logger.Printf("starting server on :%d", port) + + strPort := ":" + strconv.Itoa(port) + log.Fatal("ListenAndServe: ", http.ListenAndServe(strPort, nil)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/stats_handler.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/stats_handler.go new file mode 100644 index 0000000000000000000000000000000000000000..86153ec21c553e2c69c6b8142c1771d771a60fea --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/server/stats_handler.go @@ -0,0 +1,32 @@ +package main + +import ( + "encoding/json" + "log" + "net/http" +) + +// index for stats handle +func statsIndexHandler() http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + getCacheStatsHandler(w, r) + default: + w.WriteHeader(http.StatusMethodNotAllowed) + } + }) +} + +// returns the cache's statistics. +func getCacheStatsHandler(w http.ResponseWriter, r *http.Request) { + target, err := json.Marshal(cache.Stats()) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + log.Printf("cannot marshal cache stats. error: %s", err) + return + } + // since we're sending a struct, make it easy for consumers to interface. + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Write(target) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/shard.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/shard.go new file mode 100644 index 0000000000000000000000000000000000000000..4f03b53eaf1b0371f3df9390dd656c0d98090365 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/shard.go @@ -0,0 +1,454 @@ +package bigcache + +import ( + "errors" + "sync" + "sync/atomic" + + "github.com/allegro/bigcache/v3/queue" +) + +type onRemoveCallback func(wrappedEntry []byte, reason RemoveReason) + +// Metadata contains information of a specific entry +type Metadata struct { + RequestCount uint32 +} + +type cacheShard struct { + hashmap map[uint64]uint64 + entries queue.BytesQueue + lock sync.RWMutex + entryBuffer []byte + onRemove onRemoveCallback + + isVerbose bool + statsEnabled bool + logger Logger + clock clock + lifeWindow uint64 + + hashmapStats map[uint64]uint32 + stats Stats + cleanEnabled bool +} + +func (s *cacheShard) getWithInfo(key string, hashedKey uint64) (entry []byte, resp Response, err error) { + currentTime := uint64(s.clock.Epoch()) + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, resp, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, resp, ErrEntryNotFound + } + + entry = readEntry(wrappedEntry) + if s.isExpired(wrappedEntry, currentTime) { + resp.EntryStatus = Expired + } + s.lock.RUnlock() + s.hit(hashedKey) + return entry, resp, nil +} + +func (s *cacheShard) get(key string, hashedKey uint64) ([]byte, error) { + s.lock.RLock() + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + s.lock.RUnlock() + return nil, err + } + if entryKey := readKeyFromEntry(wrappedEntry); key != entryKey { + s.lock.RUnlock() + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, entryKey, hashedKey) + } + return nil, ErrEntryNotFound + } + entry := readEntry(wrappedEntry) + s.lock.RUnlock() + s.hit(hashedKey) + + return entry, nil +} + +func (s *cacheShard) getWrappedEntry(hashedKey uint64) ([]byte, error) { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.miss() + return nil, ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.miss() + return nil, err + } + + return wrappedEntry, err +} + +func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, error) { + wrappedEntry, err := s.getWrappedEntry(hashedKey) + if err != nil { + return nil, err + } + + if !compareKeyFromEntry(wrappedEntry, key) { + s.collision() + if s.isVerbose { + s.logger.Printf("Collision detected. Both %q and %q have the same hash %x", key, readKeyFromEntry(wrappedEntry), hashedKey) + } + + return nil, ErrEntryNotFound + } + s.hitWithoutLock(hashedKey) + + return wrappedEntry, nil +} + +func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + s.lock.Lock() + + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + //remove hashkey + delete(s.hashmap, hashedKey) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + s.lock.Unlock() + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + s.lock.Unlock() + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) addNewWithoutLock(key string, hashedKey uint64, entry []byte) error { + currentTimestamp := uint64(s.clock.Epoch()) + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + w := wrapEntry(currentTimestamp, hashedKey, key, entry, &s.entryBuffer) + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) setWrappedEntryWithoutLock(currentTimestamp uint64, w []byte, hashedKey uint64) error { + if previousIndex := s.hashmap[hashedKey]; previousIndex != 0 { + if previousEntry, err := s.entries.Get(int(previousIndex)); err == nil { + resetHashFromEntry(previousEntry) + } + } + + if !s.cleanEnabled { + if oldestEntry, err := s.entries.Peek(); err == nil { + s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry) + } + } + + for { + if index, err := s.entries.Push(w); err == nil { + s.hashmap[hashedKey] = uint64(index) + return nil + } + if s.removeOldestEntry(NoSpace) != nil { + return errors.New("entry is bigger than max shard size") + } + } +} + +func (s *cacheShard) append(key string, hashedKey uint64, entry []byte) error { + s.lock.Lock() + wrappedEntry, err := s.getValidWrapEntry(key, hashedKey) + + if err == ErrEntryNotFound { + err = s.addNewWithoutLock(key, hashedKey, entry) + s.lock.Unlock() + return err + } + if err != nil { + s.lock.Unlock() + return err + } + + currentTimestamp := uint64(s.clock.Epoch()) + + w := appendToWrappedEntry(currentTimestamp, wrappedEntry, entry, &s.entryBuffer) + + err = s.setWrappedEntryWithoutLock(currentTimestamp, w, hashedKey) + s.lock.Unlock() + + return err +} + +func (s *cacheShard) del(hashedKey uint64) error { + // Optimistic pre-check using only readlock + s.lock.RLock() + { + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.RUnlock() + s.delmiss() + return ErrEntryNotFound + } + + if err := s.entries.CheckGet(int(itemIndex)); err != nil { + s.lock.RUnlock() + s.delmiss() + return err + } + } + s.lock.RUnlock() + + s.lock.Lock() + { + // After obtaining the writelock, we need to read the same again, + // since the data delivered earlier may be stale now + itemIndex := s.hashmap[hashedKey] + + if itemIndex == 0 { + s.lock.Unlock() + s.delmiss() + return ErrEntryNotFound + } + + wrappedEntry, err := s.entries.Get(int(itemIndex)) + if err != nil { + s.lock.Unlock() + s.delmiss() + return err + } + + delete(s.hashmap, hashedKey) + s.onRemove(wrappedEntry, Deleted) + if s.statsEnabled { + delete(s.hashmapStats, hashedKey) + } + resetHashFromEntry(wrappedEntry) + } + s.lock.Unlock() + + s.delhit() + return nil +} + +func (s *cacheShard) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool { + if s.isExpired(oldestEntry, currentTimestamp) { + evict(Expired) + return true + } + return false +} + +func (s *cacheShard) isExpired(oldestEntry []byte, currentTimestamp uint64) bool { + oldestTimestamp := readTimestampFromEntry(oldestEntry) + if currentTimestamp <= oldestTimestamp { // if currentTimestamp < oldestTimestamp, the result will out of uint64 limits; + return false + } + return currentTimestamp-oldestTimestamp > s.lifeWindow +} + +func (s *cacheShard) cleanUp(currentTimestamp uint64) { + s.lock.Lock() + for { + if oldestEntry, err := s.entries.Peek(); err != nil { + break + } else if evicted := s.onEvict(oldestEntry, currentTimestamp, s.removeOldestEntry); !evicted { + break + } + } + s.lock.Unlock() +} + +func (s *cacheShard) getEntry(hashedKey uint64) ([]byte, error) { + s.lock.RLock() + + entry, err := s.getWrappedEntry(hashedKey) + // copy entry + newEntry := make([]byte, len(entry)) + copy(newEntry, entry) + + s.lock.RUnlock() + + return newEntry, err +} + +func (s *cacheShard) copyHashedKeys() (keys []uint64, next int) { + s.lock.RLock() + keys = make([]uint64, len(s.hashmap)) + + for key := range s.hashmap { + keys[next] = key + next++ + } + + s.lock.RUnlock() + return keys, next +} + +func (s *cacheShard) removeOldestEntry(reason RemoveReason) error { + oldest, err := s.entries.Pop() + if err == nil { + hash := readHashFromEntry(oldest) + if hash == 0 { + // entry has been explicitly deleted with resetHashFromEntry, ignore + return nil + } + delete(s.hashmap, hash) + s.onRemove(oldest, reason) + if s.statsEnabled { + delete(s.hashmapStats, hash) + } + return nil + } + return err +} + +func (s *cacheShard) reset(config Config) { + s.lock.Lock() + s.hashmap = make(map[uint64]uint64, config.initialShardSize()) + s.entryBuffer = make([]byte, config.MaxEntrySize+headersSizeInBytes) + s.entries.Reset() + s.lock.Unlock() +} + +func (s *cacheShard) resetStats() { + s.lock.Lock() + s.stats = Stats{} + s.lock.Unlock() +} + +func (s *cacheShard) len() int { + s.lock.RLock() + res := len(s.hashmap) + s.lock.RUnlock() + return res +} + +func (s *cacheShard) capacity() int { + s.lock.RLock() + res := s.entries.Capacity() + s.lock.RUnlock() + return res +} + +func (s *cacheShard) getStats() Stats { + var stats = Stats{ + Hits: atomic.LoadInt64(&s.stats.Hits), + Misses: atomic.LoadInt64(&s.stats.Misses), + DelHits: atomic.LoadInt64(&s.stats.DelHits), + DelMisses: atomic.LoadInt64(&s.stats.DelMisses), + Collisions: atomic.LoadInt64(&s.stats.Collisions), + } + return stats +} + +func (s *cacheShard) getKeyMetadataWithLock(key uint64) Metadata { + s.lock.RLock() + c := s.hashmapStats[key] + s.lock.RUnlock() + return Metadata{ + RequestCount: c, + } +} + +func (s *cacheShard) getKeyMetadata(key uint64) Metadata { + return Metadata{ + RequestCount: s.hashmapStats[key], + } +} + +func (s *cacheShard) hit(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.lock.Lock() + s.hashmapStats[key]++ + s.lock.Unlock() + } +} + +func (s *cacheShard) hitWithoutLock(key uint64) { + atomic.AddInt64(&s.stats.Hits, 1) + if s.statsEnabled { + s.hashmapStats[key]++ + } +} + +func (s *cacheShard) miss() { + atomic.AddInt64(&s.stats.Misses, 1) +} + +func (s *cacheShard) delhit() { + atomic.AddInt64(&s.stats.DelHits, 1) +} + +func (s *cacheShard) delmiss() { + atomic.AddInt64(&s.stats.DelMisses, 1) +} + +func (s *cacheShard) collision() { + atomic.AddInt64(&s.stats.Collisions, 1) +} + +func initNewShard(config Config, callback onRemoveCallback, clock clock) *cacheShard { + bytesQueueInitialCapacity := config.initialShardSize() * config.MaxEntrySize + maximumShardSizeInBytes := config.maximumShardSizeInBytes() + if maximumShardSizeInBytes > 0 && bytesQueueInitialCapacity > maximumShardSizeInBytes { + bytesQueueInitialCapacity = maximumShardSizeInBytes + } + return &cacheShard{ + hashmap: make(map[uint64]uint64, config.initialShardSize()), + hashmapStats: make(map[uint64]uint32, config.initialShardSize()), + entries: *queue.NewBytesQueue(bytesQueueInitialCapacity, maximumShardSizeInBytes, config.Verbose), + entryBuffer: make([]byte, config.MaxEntrySize+headersSizeInBytes), + onRemove: callback, + + isVerbose: config.Verbose, + logger: newLogger(config.Logger), + clock: clock, + lifeWindow: uint64(config.LifeWindow.Seconds()), + statsEnabled: config.StatsEnabled, + cleanEnabled: config.CleanWindow > 0, + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/stats.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/stats.go new file mode 100644 index 0000000000000000000000000000000000000000..07157132a23949a2d9443daaa2954d40f0e2b881 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/stats.go @@ -0,0 +1,15 @@ +package bigcache + +// Stats stores cache statistics +type Stats struct { + // Hits is a number of successfully found keys + Hits int64 `json:"hits"` + // Misses is a number of not found keys + Misses int64 `json:"misses"` + // DelHits is a number of successfully deleted keys + DelHits int64 `json:"delete_hits"` + // DelMisses is a number of not deleted keys + DelMisses int64 `json:"delete_misses"` + // Collisions is a number of happened key-collisions + Collisions int64 `json:"collisions"` +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/utils.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/utils.go new file mode 100644 index 0000000000000000000000000000000000000000..2f4d7a844c7942d87577dd741a044439720310ad --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/environment/source/utils.go @@ -0,0 +1,16 @@ +package bigcache + +func max(a, b int) int { + if a > b { + return a + } + return b +} + +func convertMBToBytes(value int) int { + return value * 1024 * 1024 +} + +func isPowerOfTwo(number int) bool { + return (number != 0) && (number&(number-1)) == 0 +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/instruction.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9c5e1955a043b5b1e1c5e2b7b597ad9d21055b5f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/instruction.md @@ -0,0 +1,40 @@ +OnRemoveWithReason callback not being invoked + +#### Description + +The OnRemoveWithReason callback is not being called when entries are removed from the cache, even when configured properly. This affects both filtered and unfiltered removal callbacks. + +#### Steps/Code to Reproduce + +```go +package main + +import ( + "fmt" + "time" + + "github.com/allegro/bigcache/v3" +) + +func main() { + callbackInvoked := false + + config := bigcache.DefaultConfig(time.Minute) + config.OnRemoveWithReason = func(key string, entry []byte, reason bigcache.RemoveReason) { + callbackInvoked = true + fmt.Printf("Callback invoked for key: %s, reason: %v\n", key, reason) + } + + cache, _ := bigcache.NewBigCache(config) + + cache.Set("test-key", []byte("test-value")) + cache.Delete("test-key") + + // Expected: callback should be invoked and callbackInvoked should be true + // Actual: callback is never called and callbackInvoked remains false + fmt.Printf("Callback invoked: %t\n", callbackInvoked) +} +``` + +The same issue occurs when using OnRemoveFilter to selectively invoke callbacks for specific removal reasons - the callback is never executed regardless of the filter configuration. +Work in /testbed. This is a broken source-only export without Git history or tests. Grading restores frozen private tests independently. Repair existing implementation files; new arbitrary files are outside the current transfer contract. Offline Go dependencies are preinstalled. diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/provenance.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..c2905905e357a16f20ae6d27a879b6c943543c7b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/provenance.json @@ -0,0 +1,362 @@ +{ + "cloud_launch_ready": false, + "execution_command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "execution_profile": "harbor-semantic-jobs-v1", + "full_rfc008": false, + "generated_reference": false, + "native_validation_performed": false, + "negative_classes": { + "delete-tests": "same wrong implementation with verifier deletion/stdout spoof attempt", + "original-bug": "task-specific unchanged semantic bug", + "stale-reward": "same wrong implementation with stale reward spoof attempt" + }, + "new_arbitrary_files_supported": false, + "partial_hunk_control": { + "basis": "single-hunk original-bug canary is NOP-equivalent; other canaries test abuse classes only", + "extra_semantic_repair_coverage": false, + "original_patch_hunks": 1 + }, + "private_frozen_files": { + "assert_test.go": { + "mode": "0o644", + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161", + "size": 1056 + }, + "bigcache_bench_test.go": { + "mode": "0o644", + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f", + "size": 4889 + }, + "bigcache_test.go": { + "mode": "0o644", + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67", + "size": 29443 + }, + "encoding_test.go": { + "mode": "0o644", + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918", + "size": 1011 + }, + "examples_test.go": { + "mode": "0o644", + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953", + "size": 2470 + }, + "fnv_bench_test.go": { + "mode": "0o644", + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e", + "size": 281 + }, + "fnv_test.go": { + "mode": "0o644", + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8", + "size": 743 + }, + "hash_test.go": { + "mode": "0o644", + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a", + "size": 109 + }, + "iterator_test.go": { + "mode": "0o644", + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef", + "size": 5006 + }, + "queue/bytes_queue_test.go": { + "mode": "0o644", + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099", + "size": 11775 + }, + "server/middleware_test.go": { + "mode": "0o644", + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8", + "size": 1179 + }, + "server/server_test.go": { + "mode": "0o644", + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906", + "size": 8224 + } + }, + "public_files": { + ".codecov.yml": { + "mode": "0o644", + "sha256": "8e707ec1a3f0ceffcb43878673454a06e4b9d67cf86d48049c5b85c9ccf7ba7f", + "size": 471 + }, + ".github/CODEOWNERS": { + "mode": "0o644", + "sha256": "cdcba8c23ea8e66127e1cd1bef9c781b4934bcd183a8610785c190c98100429c", + "size": 23 + }, + ".github/ISSUE_TEMPLATE/issue_template.md": { + "mode": "0o644", + "sha256": "f72d2c8e4b6eace27561d0f9dfba9af3adfb839cfee3db8894e1fe67b5f4035e", + "size": 882 + }, + ".github/dependabot.yml": { + "mode": "0o644", + "sha256": "8c37eb22b937057d6f19395f38fba2134b1ba842cab0aef23ffd789bf1b148b6", + "size": 276 + }, + ".github/release-drafter.yml": { + "mode": "0o644", + "sha256": "bce147dfd3f8dc9aebf2ec3939974e3d0fe793a92adbd1c2581b18174404a4bd", + "size": 390 + }, + ".gitignore": { + "mode": "0o644", + "sha256": "1a7633912508968300ece4481b6deee44eca16a86cad004b3e7219e259fc828a", + "size": 183 + }, + ".golangci.yaml": { + "mode": "0o644", + "sha256": "09452084d6a5b5f78def8c7ff0f314b51e6e21ba11177afee3efe98a933d3b82", + "size": 438 + }, + "LICENSE": { + "mode": "0o644", + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "size": 11357 + }, + "README.md": { + "mode": "0o644", + "sha256": "d0410d1ee7ee43e5c7f4b730c544de6d51f9466136696944cf0e3574a5d532a6", + "size": 8598 + }, + "bigcache.go": { + "mode": "0o644", + "sha256": "60d9872bb6c54a98da50908ded7a2cabb44c6c9eb184c2e9b424766f48ccd2a4", + "size": 7704 + }, + "bytes.go": { + "mode": "0o644", + "sha256": "6916cf679ae9f23d393efdaba786319f22658f1bafde4b803bb2afa9803eb28c", + "size": 163 + }, + "bytes_appengine.go": { + "mode": "0o644", + "sha256": "f5caf9266f5938f86b041ab3ea213c32e337ca714cc7909664a4a1aeaff14262", + "size": 118 + }, + "clock.go": { + "mode": "0o644", + "sha256": "f9907860f15b4b6a4f02799b07698a6c8c30b61de3b5717ca647817d49317498", + "size": 168 + }, + "config.go": { + "mode": "0o644", + "sha256": "fe08d8a488b9c5eeff7ce41c534b0a1bed750299c7249b17216179d9fc6791d0", + "size": 4375 + }, + "encoding.go": { + "mode": "0o644", + "sha256": "30c3c86195f458a6c50183ed38defb05d4fc891fa2abc2ec59b5eef4cc8d0443", + "size": 2629 + }, + "entry_not_found_error.go": { + "mode": "0o644", + "sha256": "e6fa4ea655f302b24ea79ac524df9a632a53736a7b3bb9483498816140060144", + "size": 198 + }, + "fnv.go": { + "mode": "0o644", + "sha256": "b65cda8dd5b148fccc230c7e6176505cba4d2070f58b060a24754b137f48f3c1", + "size": 837 + }, + "go.mod": { + "mode": "0o644", + "sha256": "ed4d0d499d3807bb65b3bb2b06b927922a09a593e2cabbc9e55468e9b86c0129", + "size": 47 + }, + "go.sum": { + "mode": "0o644", + "sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "size": 0 + }, + "hash.go": { + "mode": "0o644", + "sha256": "e0b9382e30e98089a30782a8098d38ed628a46e4fda9ddf5fc1cf12344e03008", + "size": 339 + }, + "iterator.go": { + "mode": "0o644", + "sha256": "6770e3ddf57fd7ef15c8069f5a9c172c6c34497108e2fe53f9a764f30cddf0db", + "size": 3232 + }, + "logger.go": { + "mode": "0o644", + "sha256": "ab90b4bc9a2348109d3e3bb5f7486b77f0289b0e73ed348646ca4f725aa907d5", + "size": 635 + }, + "queue/bytes_queue.go": { + "mode": "0o644", + "sha256": "d1926bf6ca357883279dc6b6bc575839606763c67267598922cda4af6eaeca21", + "size": 6856 + }, + "server/README.md": { + "mode": "0o644", + "sha256": "31c6d36457f918e64c2c197e85c68486b31703d0975813d11bbe3e055e2200f4", + "size": 3383 + }, + "server/cache_handlers.go": { + "mode": "0o644", + "sha256": "3fc826f897cd76cb2da4b23d415c1565a2b7afaf9d4ecfc84d4b08b5775cb891", + "size": 2452 + }, + "server/middleware.go": { + "mode": "0o644", + "sha256": "7036cb032f39e2df51c754de8682edf630b998de15cd42ddaa58cb5d0e2fdd88", + "size": 653 + }, + "server/server.go": { + "mode": "0o644", + "sha256": "1be684e9df49bc5d13148c6d0414add246eed51ea427893ed7767ba224132302", + "size": 2302 + }, + "server/stats_handler.go": { + "mode": "0o644", + "sha256": "69cfc624f705514c30603b35d595ba6226ce1157358410218263512a9a2a0caa", + "size": 785 + }, + "shard.go": { + "mode": "0o644", + "sha256": "d329f4dae7630ca29e2b3731f3c8030020242f033794aa689f7ed1f0822b9e98", + "size": 10768 + }, + "stats.go": { + "mode": "0o644", + "sha256": "f367500e1cb51b62cf8ad6d0a7b6f5aecf7338d30b85ea5b87ddd94e5315acbc", + "size": 485 + }, + "utils.go": { + "mode": "0o644", + "sha256": "709a85c5e06f0600b59e5732985f13bb948c064b5f0ab65b7a66696c1068794a", + "size": 241 + } + }, + "reference_kind": "provided_healthy_parent_changed_implementation", + "runtime": { + "clean_runtime_qualified": false, + "config": { + "architecture": "amd64", + "digest": "sha256:179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3", + "os": "linux", + "sha256": "179b97eadd1480cf86d783661f2e06f7aeff205ca04e87968931c2f79346ebe3" + }, + "context_inventory_sha256": "47a84fa25684316dd81c22007938b54a0391ae4f6c87c0a455be3c3dc3caff88", + "image": "registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "image_pull_qualified": false, + "provider_image_source_attestation": false, + "publication_receipt_sha256": "f7d72d78029fcfa7d9cc529617f0d9050c5bf6dd23c2770c9cde8992e045f20f", + "receipt_path": "production/runtime-images-v1/resolutions/171eb7c4b9b75f3f/resolution.json", + "receipt_sha256": "60a6e671183c0cee0f810534801f08cd4310ab8f4b2b22139aa624fc64294a0c", + "registry_digest": "sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d", + "source_image": "docker.io/swebench/swesmith.x86_64.allegro_1776_bigcache.5aa251c4@sha256:d011803cbd9412964ac36ff238c725ab5334648208aeaea593c169d55d604b0f", + "source_receipt_sha256": "60267ec17e61defad2974d1ebd52882b1b3161c8088519c025cf22c208854669", + "space_commit": "e1c640c73aca9d561fac6e7c93e70a674de018d5", + "space_id": "harness-hub/scale800-171eb7c4b9b75f3f-starter-v1", + "status": "registry_resolved_paused_unqualified" + }, + "schema": "scale800-go-jobs-transform-v1", + "source_completion_sha256": "5f610e943724c89e8821480b4131d17a76c702e17ad02db54a511556a631c64a", + "source_index_sha256": "c6a579667a10d7d11f14285e2bc349086351d67c49a8f378c797c819dea8a47f", + "source_inventory_verified": true, + "source_manifest_sha256": "bbe28efe04f8ddfc9f0e102d045abdb4509895b301302f06ffb08f5878627a21", + "source_proof_sha256": "2db7396f066c113487f31979e8ed35646cbcb2835f96e3acce39014068281fb4", + "source_record": { + "anti_training_canary": false, + "anti_training_reviewed": true, + "candidate_id": "swesmith-go:allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn", + "cloud_launch_ready": false, + "healthy_mirror_commit": "532039148219a0d9ae2f2d5738e442f00e61b1d8", + "instruction_sha256": "ed117eef1941b26f13e81cbed6e0715983c3a3f7c540326462407155ccdcdfe2", + "is_fork": true, + "learner_path": "tasks/3c2398073dc4359565f24637/learner", + "license_evidence": { + "source_code": { + "reviewed": true, + "sha256": "b40930bbcf80744c86c46a12bc9da056641d722716c378f5659b9e555ef833e1", + "spdx": "Apache-2.0", + "training_allowed": true, + "url": "https://raw.githubusercontent.com/swesmith/allegro__bigcache.5aa251c4/23a2fca0ee1fee8bd82288a1724787c245c3160c/LICENSE" + }, + "task_bundle": { + "basis": "Captured publisher MIT/train declaration; exact software permission separately checked per source", + "reviewed": true, + "sha256": "2e917153213a0f11a6d0f314e87d8092eb8289ae4dc767cdc020d024c7d5339f", + "spdx": "MIT", + "training_allowed": true, + "url": "https://huggingface.co/api/datasets/SWE-bench/SWE-smith-go/revision/d2f6ecc2cf8ae1af00fc790801bbacfa2913e015" + } + }, + "original_source_commit": "5aa251c4cc3d607bbb48b825ef583ad1fafa1845", + "patch_sha256": "744c1c65bd2d7feb180403ef6222e98539feecdff3fe3b74fc048ead31973bcc", + "provenance_path": "tasks/3c2398073dc4359565f24637/source-proof.json", + "repository_lineage": [ + "swesmith/allegro__bigcache.5aa251c4", + "allegro/bigcache" + ], + "rfc008_complete": false, + "runtime_qualified": false, + "runtime_test_identity_status": "pending_runtime_test_identity_resolution", + "semantic_nonoverlap_established": false, + "source_commit": "23a2fca0ee1fee8bd82288a1724787c245c3160c", + "source_dataset": "SWE-bench/SWE-smith-go", + "source_head_commit": "68effa663ffc962578e15ee90d4e4acd3e5fc023", + "source_kind": "mutation", + "source_repo": "swesmith/allegro__bigcache.5aa251c4", + "source_revision": "d2f6ecc2cf8ae1af00fc790801bbacfa2913e015", + "source_split": "train", + "target_model_calibrated": false, + "task_id": "allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn", + "task_sha256": "0157d48cbd745fffcee2bca745ecd463fc1ed1e377f6e06d77c37babe69a86e7", + "training_admissible": false, + "upstream_identity_reviewed": true, + "upstream_repo": "allegro/bigcache", + "usage": "quarantine_only" + }, + "source_row_sha256": "3ea561da8de4088d6b217923b1657593c2a4f442cff4f96ff8a1a5d040dc474e", + "source_test_command": "go test -v ./...", + "target_model_calibrated": false, + "training_admissible": false, + "transfer_allowlist": [ + "/testbed/.codecov.yml", + "/testbed/.github/CODEOWNERS", + "/testbed/.github/ISSUE_TEMPLATE/issue_template.md", + "/testbed/.github/dependabot.yml", + "/testbed/.github/release-drafter.yml", + "/testbed/.gitignore", + "/testbed/.golangci.yaml", + "/testbed/LICENSE", + "/testbed/README.md", + "/testbed/bigcache.go", + "/testbed/bytes.go", + "/testbed/bytes_appengine.go", + "/testbed/clock.go", + "/testbed/config.go", + "/testbed/encoding.go", + "/testbed/entry_not_found_error.go", + "/testbed/fnv.go", + "/testbed/go.mod", + "/testbed/go.sum", + "/testbed/hash.go", + "/testbed/iterator.go", + "/testbed/logger.go", + "/testbed/queue/bytes_queue.go", + "/testbed/server/README.md", + "/testbed/server/cache_handlers.go", + "/testbed/server/middleware.go", + "/testbed/server/server.go", + "/testbed/server/stats_handler.go", + "/testbed/shard.go", + "/testbed/stats.go", + "/testbed/utils.go" + ] +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/solution/solve.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e20771b34c4feaadd38f3aa1c59b581fe4d7ea5a --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/solution/solve.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -eu +/usr/local/bin/python -I - <<'OPENENV_REFERENCE' +import base64,json +from pathlib import Path +files=json.loads('{"bigcache.go": {"data": "cGFja2FnZSBiaWdjYWNoZQoKaW1wb3J0ICgKCSJjb250ZXh0IgoJImVycm9ycyIKCSJ0aW1lIgopCgpjb25zdCAoCgltaW5pbXVtRW50cmllc0luU2hhcmQgPSAxMCAvLyBNaW5pbXVtIG51bWJlciBvZiBlbnRyaWVzIGluIHNpbmdsZSBzaGFyZAopCgovLyBCaWdDYWNoZSBpcyBmYXN0LCBjb25jdXJyZW50LCBldmljdGluZyBjYWNoZSBjcmVhdGVkIHRvIGtlZXAgYmlnIG51bWJlciBvZiBlbnRyaWVzIHdpdGhvdXQgaW1wYWN0IG9uIHBlcmZvcm1hbmNlLgovLyBJdCBrZWVwcyBlbnRyaWVzIG9uIGhlYXAgYnV0IG9taXRzIEdDIGZvciB0aGVtLiBUbyBhY2hpZXZlIHRoYXQsIG9wZXJhdGlvbnMgdGFrZSBwbGFjZSBvbiBieXRlIGFycmF5cywKLy8gdGhlcmVmb3JlIGVudHJpZXMgKGRlKXNlcmlhbGl6YXRpb24gaW4gZnJvbnQgb2YgdGhlIGNhY2hlIHdpbGwgYmUgbmVlZGVkIGluIG1vc3QgdXNlIGNhc2VzLgp0eXBlIEJpZ0NhY2hlIHN0cnVjdCB7CglzaGFyZHMgICAgIFtdKmNhY2hlU2hhcmQKCWxpZmVXaW5kb3cgdWludDY0CgljbG9jayAgICAgIGNsb2NrCgloYXNoICAgICAgIEhhc2hlcgoJY29uZmlnICAgICBDb25maWcKCXNoYXJkTWFzayAgdWludDY0CgljbG9zZSAgICAgIGNoYW4gc3RydWN0e30KfQoKLy8gUmVzcG9uc2Ugd2lsbCBjb250YWluIG1ldGFkYXRhIGFib3V0IHRoZSBlbnRyeSBmb3Igd2hpY2ggR2V0V2l0aEluZm8oa2V5KSB3YXMgY2FsbGVkCnR5cGUgUmVzcG9uc2Ugc3RydWN0IHsKCUVudHJ5U3RhdHVzIFJlbW92ZVJlYXNvbgp9CgovLyBSZW1vdmVSZWFzb24gaXMgYSB2YWx1ZSB1c2VkIHRvIHNpZ25hbCB0byB0aGUgdXNlciB3aHkgYSBwYXJ0aWN1bGFyIGtleSB3YXMgcmVtb3ZlZCBpbiB0aGUgT25SZW1vdmUgY2FsbGJhY2suCnR5cGUgUmVtb3ZlUmVhc29uIHVpbnQzMgoKY29uc3QgKAoJLy8gRXhwaXJlZCBtZWFucyB0aGUga2V5IGlzIHBhc3QgaXRzIExpZmVXaW5kb3cuCglFeHBpcmVkID0gUmVtb3ZlUmVhc29uKDEpCgkvLyBOb1NwYWNlIG1lYW5zIHRoZSBrZXkgaXMgdGhlIG9sZGVzdCBhbmQgdGhlIGNhY2hlIHNpemUgd2FzIGF0IGl0cyBtYXhpbXVtIHdoZW4gU2V0IHdhcyBjYWxsZWQsIG9yIHRoZQoJLy8gZW50cnkgZXhjZWVkZWQgdGhlIG1heGltdW0gc2hhcmQgc2l6ZS4KCU5vU3BhY2UgPSBSZW1vdmVSZWFzb24oMikKCS8vIERlbGV0ZWQgbWVhbnMgRGVsZXRlIHdhcyBjYWxsZWQgYW5kIHRoaXMga2V5IHdhcyByZW1vdmVkIGFzIGEgcmVzdWx0LgoJRGVsZXRlZCA9IFJlbW92ZVJlYXNvbigzKQopCgovLyBOZXcgaW5pdGlhbGl6ZSBuZXcgaW5zdGFuY2Ugb2YgQmlnQ2FjaGUKZnVuYyBOZXcoY3R4IGNvbnRleHQuQ29udGV4dCwgY29uZmlnIENvbmZpZykgKCpCaWdDYWNoZSwgZXJyb3IpIHsKCXJldHVybiBuZXdCaWdDYWNoZShjdHgsIGNvbmZpZywgJnN5c3RlbUNsb2Nre30pCn0KCi8vIE5ld0JpZ0NhY2hlIGluaXRpYWxpemUgbmV3IGluc3RhbmNlIG9mIEJpZ0NhY2hlCi8vCi8vIERlcHJlY2F0ZWQ6IE5ld0JpZ0NhY2hlIGlzIGRlcHJlY2F0ZWQsIHBsZWFzZSB1c2UgTmV3KGN0eCwgY29uZmlnKSBpbnN0ZWFkLAovLyBOZXcgdGFrZXMgaW4gY29udGV4dCBhbmQgY2FuIGdyYWNlZnVsbHkKLy8gc2h1dGRvd24gd2l0aCBjb250ZXh0IGNhbmNlbGxhdGlvbnMKZnVuYyBOZXdCaWdDYWNoZShjb25maWcgQ29uZmlnKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJcmV0dXJuIG5ld0JpZ0NhY2hlKGNvbnRleHQuQmFja2dyb3VuZCgpLCBjb25maWcsICZzeXN0ZW1DbG9ja3t9KQp9CgpmdW5jIG5ld0JpZ0NhY2hlKGN0eCBjb250ZXh0LkNvbnRleHQsIGNvbmZpZyBDb25maWcsIGNsb2NrIGNsb2NrKSAoKkJpZ0NhY2hlLCBlcnJvcikgewoJaWYgIWlzUG93ZXJPZlR3byhjb25maWcuU2hhcmRzKSB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiU2hhcmRzIG51bWJlciBtdXN0IGJlIHBvd2VyIG9mIHR3byIpCgl9CglpZiBjb25maWcuTWF4RW50cnlTaXplIDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cnlTaXplIG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuTWF4RW50cmllc0luV2luZG93IDwgMCB7CgkJcmV0dXJuIG5pbCwgZXJyb3JzLk5ldygiTWF4RW50cmllc0luV2luZG93IG11c3QgYmUgPj0gMCIpCgl9CglpZiBjb25maWcuSGFyZE1heENhY2hlU2l6ZSA8IDAgewoJCXJldHVybiBuaWwsIGVycm9ycy5OZXcoIkhhcmRNYXhDYWNoZVNpemUgbXVzdCBiZSA+PSAwIikKCX0KCglsaWZlV2luZG93U2Vjb25kcyA6PSB1aW50NjQoY29uZmlnLkxpZmVXaW5kb3cuU2Vjb25kcygpKQoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCAmJiBsaWZlV2luZG93U2Vjb25kcyA9PSAwIHsKCQlyZXR1cm4gbmlsLCBlcnJvcnMuTmV3KCJMaWZlV2luZG93IG11c3QgYmUgPj0gMXMgd2hlbiBDbGVhbldpbmRvdyBpcyBzZXQiKQoJfQoKCWlmIGNvbmZpZy5IYXNoZXIgPT0gbmlsIHsKCQljb25maWcuSGFzaGVyID0gbmV3RGVmYXVsdEhhc2hlcigpCgl9CgoJY2FjaGUgOj0gJkJpZ0NhY2hlewoJCXNoYXJkczogICAgIG1ha2UoW10qY2FjaGVTaGFyZCwgY29uZmlnLlNoYXJkcyksCgkJbGlmZVdpbmRvdzogbGlmZVdpbmRvd1NlY29uZHMsCgkJY2xvY2s6ICAgICAgY2xvY2ssCgkJaGFzaDogICAgICAgY29uZmlnLkhhc2hlciwKCQljb25maWc6ICAgICBjb25maWcsCgkJc2hhcmRNYXNrOiAgdWludDY0KGNvbmZpZy5TaGFyZHMgLSAxKSwKCQljbG9zZTogICAgICBtYWtlKGNoYW4gc3RydWN0e30pLAoJfQoKCXZhciBvblJlbW92ZSBmdW5jKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pCglpZiBjb25maWcuT25SZW1vdmVXaXRoTWV0YWRhdGEgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmVXaXRoTWV0YWRhdGEKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmUgIT0gbmlsIHsKCQlvblJlbW92ZSA9IGNhY2hlLnByb3ZpZGVkT25SZW1vdmUKCX0gZWxzZSBpZiBjb25maWcuT25SZW1vdmVXaXRoUmVhc29uICE9IG5pbCB7CgkJb25SZW1vdmUgPSBjYWNoZS5wcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbgoJfSBlbHNlIHsKCQlvblJlbW92ZSA9IGNhY2hlLm5vdFByb3ZpZGVkT25SZW1vdmUKCX0KCglmb3IgaSA6PSAwOyBpIDwgY29uZmlnLlNoYXJkczsgaSsrIHsKCQljYWNoZS5zaGFyZHNbaV0gPSBpbml0TmV3U2hhcmQoY29uZmlnLCBvblJlbW92ZSwgY2xvY2spCgl9CgoJaWYgY29uZmlnLkNsZWFuV2luZG93ID4gMCB7CgkJZ28gZnVuYygpIHsKCQkJdGlja2VyIDo9IHRpbWUuTmV3VGlja2VyKGNvbmZpZy5DbGVhbldpbmRvdykKCQkJZGVmZXIgdGlja2VyLlN0b3AoKQoJCQlmb3IgewoJCQkJc2VsZWN0IHsKCQkJCWNhc2UgPC1jdHguRG9uZSgpOgoJCQkJCXJldHVybgoJCQkJY2FzZSB0IDo9IDwtdGlja2VyLkM6CgkJCQkJY2FjaGUuY2xlYW5VcCh1aW50NjQodC5Vbml4KCkpKQoJCQkJY2FzZSA8LWNhY2hlLmNsb3NlOgoJCQkJCXJldHVybgoJCQkJfQoJCQl9CgkJfSgpCgl9CgoJcmV0dXJuIGNhY2hlLCBuaWwKfQoKLy8gQ2xvc2UgaXMgdXNlZCB0byBzaWduYWwgYSBzaHV0ZG93biBvZiB0aGUgY2FjaGUgd2hlbiB5b3UgYXJlIGRvbmUgd2l0aCBpdC4KLy8gVGhpcyBhbGxvd3MgdGhlIGNsZWFuaW5nIGdvcm91dGluZXMgdG8gZXhpdCBhbmQgZW5zdXJlcyByZWZlcmVuY2VzIGFyZSBub3QKLy8ga2VwdCB0byB0aGUgY2FjaGUgcHJldmVudGluZyBHQyBvZiB0aGUgZW50aXJlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2xvc2UoKSBlcnJvciB7CgljbG9zZShjLmNsb3NlKQoJcmV0dXJuIG5pbAp9CgovLyBHZXQgcmVhZHMgZW50cnkgZm9yIHRoZSBrZXkuCi8vIEl0IHJldHVybnMgYW4gRXJyRW50cnlOb3RGb3VuZCB3aGVuCi8vIG5vIGVudHJ5IGV4aXN0cyBmb3IgdGhlIGdpdmVuIGtleS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEdldChrZXkgc3RyaW5nKSAoW11ieXRlLCBlcnJvcikgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5nZXQoa2V5LCBoYXNoZWRLZXkpCn0KCi8vIEdldFdpdGhJbmZvIHJlYWRzIGVudHJ5IGZvciB0aGUga2V5IHdpdGggUmVzcG9uc2UgaW5mby4KLy8gSXQgcmV0dXJucyBhbiBFcnJFbnRyeU5vdEZvdW5kIHdoZW4KLy8gbm8gZW50cnkgZXhpc3RzIGZvciB0aGUgZ2l2ZW4ga2V5LgpmdW5jIChjICpCaWdDYWNoZSkgR2V0V2l0aEluZm8oa2V5IHN0cmluZykgKFtdYnl0ZSwgUmVzcG9uc2UsIGVycm9yKSB7CgloYXNoZWRLZXkgOj0gYy5oYXNoLlN1bTY0KGtleSkKCXNoYXJkIDo9IGMuZ2V0U2hhcmQoaGFzaGVkS2V5KQoJcmV0dXJuIHNoYXJkLmdldFdpdGhJbmZvKGtleSwgaGFzaGVkS2V5KQp9CgovLyBTZXQgc2F2ZXMgZW50cnkgdW5kZXIgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgU2V0KGtleSBzdHJpbmcsIGVudHJ5IFtdYnl0ZSkgZXJyb3IgewoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCXJldHVybiBzaGFyZC5zZXQoa2V5LCBoYXNoZWRLZXksIGVudHJ5KQp9CgovLyBBcHBlbmQgYXBwZW5kcyBlbnRyeSB1bmRlciB0aGUga2V5IGlmIGtleSBleGlzdHMsIG90aGVyd2lzZQovLyBpdCB3aWxsIHNldCB0aGUga2V5IChzYW1lIGJlaGF2aW91ciBhcyBTZXQoKSkuIFdpdGggQXBwZW5kKCkgeW91IGNhbgovLyBjb25jYXRlbmF0ZSBtdWx0aXBsZSBlbnRyaWVzIHVuZGVyIHRoZSBzYW1lIGtleSBpbiBhIGxvY2stb3B0aW1pemVkIHdheS4KZnVuYyAoYyAqQmlnQ2FjaGUpIEFwcGVuZChrZXkgc3RyaW5nLCBlbnRyeSBbXWJ5dGUpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuYXBwZW5kKGtleSwgaGFzaGVkS2V5LCBlbnRyeSkKfQoKLy8gRGVsZXRlIHJlbW92ZXMgdGhlIGtleQpmdW5jIChjICpCaWdDYWNoZSkgRGVsZXRlKGtleSBzdHJpbmcpIGVycm9yIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZGVsKGhhc2hlZEtleSkKfQoKLy8gUmVzZXQgZW1wdGllcyBhbGwgY2FjaGUgc2hhcmRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldCgpIGVycm9yIHsKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJc2hhcmQucmVzZXQoYy5jb25maWcpCgl9CglyZXR1cm4gbmlsCn0KCi8vIFJlc2V0U3RhdHMgcmVzZXRzIGNhY2hlIHN0YXRzCmZ1bmMgKGMgKkJpZ0NhY2hlKSBSZXNldFN0YXRzKCkgZXJyb3IgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5yZXNldFN0YXRzKCkKCX0KCXJldHVybiBuaWwKfQoKLy8gTGVuIGNvbXB1dGVzIHRoZSBudW1iZXIgb2YgZW50cmllcyBpbiB0aGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBMZW4oKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmxlbigpCgl9CglyZXR1cm4gbGVuCn0KCi8vIENhcGFjaXR5IHJldHVybnMgdGhlIGFtb3VudCBvZiBieXRlcyBzdG9yZWQgaW4gdGhlIGNhY2hlLgpmdW5jIChjICpCaWdDYWNoZSkgQ2FwYWNpdHkoKSBpbnQgewoJdmFyIGxlbiBpbnQKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJbGVuICs9IHNoYXJkLmNhcGFjaXR5KCkKCX0KCXJldHVybiBsZW4KfQoKLy8gU3RhdHMgcmV0dXJucyBjYWNoZSdzIHN0YXRpc3RpY3MKZnVuYyAoYyAqQmlnQ2FjaGUpIFN0YXRzKCkgU3RhdHMgewoJdmFyIHMgU3RhdHMKCWZvciBfLCBzaGFyZCA6PSByYW5nZSBjLnNoYXJkcyB7CgkJdG1wIDo9IHNoYXJkLmdldFN0YXRzKCkKCQlzLkhpdHMgKz0gdG1wLkhpdHMKCQlzLk1pc3NlcyArPSB0bXAuTWlzc2VzCgkJcy5EZWxIaXRzICs9IHRtcC5EZWxIaXRzCgkJcy5EZWxNaXNzZXMgKz0gdG1wLkRlbE1pc3NlcwoJCXMuQ29sbGlzaW9ucyArPSB0bXAuQ29sbGlzaW9ucwoJfQoJcmV0dXJuIHMKfQoKLy8gS2V5TWV0YWRhdGEgcmV0dXJucyBudW1iZXIgb2YgdGltZXMgYSBjYWNoZWQgcmVzb3VyY2Ugd2FzIHJlcXVlc3RlZC4KZnVuYyAoYyAqQmlnQ2FjaGUpIEtleU1ldGFkYXRhKGtleSBzdHJpbmcpIE1ldGFkYXRhIHsKCWhhc2hlZEtleSA6PSBjLmhhc2guU3VtNjQoa2V5KQoJc2hhcmQgOj0gYy5nZXRTaGFyZChoYXNoZWRLZXkpCglyZXR1cm4gc2hhcmQuZ2V0S2V5TWV0YWRhdGFXaXRoTG9jayhoYXNoZWRLZXkpCn0KCi8vIEl0ZXJhdG9yIHJldHVybnMgaXRlcmF0b3IgZnVuY3Rpb24gdG8gaXRlcmF0ZSBvdmVyIEVudHJ5SW5mbydzIGZyb20gd2hvbGUgY2FjaGUuCmZ1bmMgKGMgKkJpZ0NhY2hlKSBJdGVyYXRvcigpICpFbnRyeUluZm9JdGVyYXRvciB7CglyZXR1cm4gbmV3SXRlcmF0b3IoYykKfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG9uRXZpY3Qob2xkZXN0RW50cnkgW11ieXRlLCBjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCwgZXZpY3QgZnVuYyhyZWFzb24gUmVtb3ZlUmVhc29uKSBlcnJvcikgYm9vbCB7CglvbGRlc3RUaW1lc3RhbXAgOj0gcmVhZFRpbWVzdGFtcEZyb21FbnRyeShvbGRlc3RFbnRyeSkKCWlmIGN1cnJlbnRUaW1lc3RhbXAgPCBvbGRlc3RUaW1lc3RhbXAgewoJCXJldHVybiBmYWxzZQoJfQoJaWYgY3VycmVudFRpbWVzdGFtcC1vbGRlc3RUaW1lc3RhbXAgPiBjLmxpZmVXaW5kb3cgewoJCWV2aWN0KEV4cGlyZWQpCgkJcmV0dXJuIHRydWUKCX0KCXJldHVybiBmYWxzZQp9CgpmdW5jIChjICpCaWdDYWNoZSkgY2xlYW5VcChjdXJyZW50VGltZXN0YW1wIHVpbnQ2NCkgewoJZm9yIF8sIHNoYXJkIDo9IHJhbmdlIGMuc2hhcmRzIHsKCQlzaGFyZC5jbGVhblVwKGN1cnJlbnRUaW1lc3RhbXApCgl9Cn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBnZXRTaGFyZChoYXNoZWRLZXkgdWludDY0KSAoc2hhcmQgKmNhY2hlU2hhcmQpIHsKCXJldHVybiBjLnNoYXJkc1toYXNoZWRLZXkmYy5zaGFyZE1hc2tdCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlKHdyYXBwZWRFbnRyeSBbXWJ5dGUsIHJlYXNvbiBSZW1vdmVSZWFzb24pIHsKCWMuY29uZmlnLk9uUmVtb3ZlKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSkpCn0KCmZ1bmMgKGMgKkJpZ0NhY2hlKSBwcm92aWRlZE9uUmVtb3ZlV2l0aFJlYXNvbih3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglpZiBjLmNvbmZpZy5vblJlbW92ZUZpbHRlciA9PSAwIHx8ICgxPDx1aW50KHJlYXNvbikpJmMuY29uZmlnLm9uUmVtb3ZlRmlsdGVyID4gMCB7CgkJYy5jb25maWcuT25SZW1vdmVXaXRoUmVhc29uKHJlYWRLZXlGcm9tRW50cnkod3JhcHBlZEVudHJ5KSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHJlYXNvbikKCX0KfQoKZnVuYyAoYyAqQmlnQ2FjaGUpIG5vdFByb3ZpZGVkT25SZW1vdmUod3JhcHBlZEVudHJ5IFtdYnl0ZSwgcmVhc29uIFJlbW92ZVJlYXNvbikgewp9CgpmdW5jIChjICpCaWdDYWNoZSkgcHJvdmlkZWRPblJlbW92ZVdpdGhNZXRhZGF0YSh3cmFwcGVkRW50cnkgW11ieXRlLCByZWFzb24gUmVtb3ZlUmVhc29uKSB7CglrZXkgOj0gcmVhZEtleUZyb21FbnRyeSh3cmFwcGVkRW50cnkpCgoJaGFzaGVkS2V5IDo9IGMuaGFzaC5TdW02NChrZXkpCglzaGFyZCA6PSBjLmdldFNoYXJkKGhhc2hlZEtleSkKCWMuY29uZmlnLk9uUmVtb3ZlV2l0aE1ldGFkYXRhKGtleSwgcmVhZEVudHJ5KHdyYXBwZWRFbnRyeSksIHNoYXJkLmdldEtleU1ldGFkYXRhKGhhc2hlZEtleSkpCn0K", "mode": 420}}') +for name,item in files.items(): + p=Path('/testbed')/name + p.parent.mkdir(parents=True,exist_ok=True) + p.write_bytes(base64.b64decode(item['data'])) + p.chmod(item['mode']) +OPENENV_REFERENCE diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/task.toml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2933019ff80c454c8a8d995b64e148db60d68010 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/task.toml @@ -0,0 +1,11 @@ +version = "1.0" +[agent] +timeout_sec = 300.0 +[verifier] +timeout_sec = 300.0 +environment_mode = "shared" +[environment] +docker_image = "ghcr.io/younesbelkada/scale800@sha256:85ca7a540af0eb788f850af879940a405b9c6b2c0747d92c1d61cec4288212f0" +cpus = 1 +memory_mb = 2048 +storage_mb = 4096 diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/assert_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/assert_test.go new file mode 100644 index 0000000000000000000000000000000000000000..940011fa7b352e5e4e9e2639067c4fc1762313f0 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/assert_test.go @@ -0,0 +1,50 @@ +package bigcache + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/bigcache_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/bigcache_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..b6d044e51d98beab772d587dfe9f97cdbd4eb0be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/bigcache_bench_test.go @@ -0,0 +1,210 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "strconv" + "testing" + "time" +) + +var message = blob('a', 256) + +func BenchmarkWriteToCacheWith1Shard(b *testing.B) { + writeToCache(b, 1, 100*time.Second, b.N) +} + +func BenchmarkWriteToLimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToUnlimitedCacheWithSmallInitSizeAnd1Shard(b *testing.B) { + m := blob('a', 1024) + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + }) + + b.ReportAllocs() + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } +} + +func BenchmarkWriteToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + writeToCache(b, shards, 100*time.Second, b.N) + }) + } +} +func BenchmarkAppendToCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + appendToCache(b, shards, 100*time.Second, b.N) + }) + } +} + +func BenchmarkReadFromCache(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, false) + }) + } +} + +func BenchmarkReadFromCacheWithInfo(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCache(b, shards, true) + }) + } +} +func BenchmarkIterateOverCache(b *testing.B) { + + m := blob('a', 1) + + for _, shards := range []int{512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + + for i := 0; i < b.N; i++ { + cache.Set(fmt.Sprintf("key-%d", i), m) + } + + b.ResetTimer() + it := cache.Iterator() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if it.SetNext() { + it.Value() + } + } + }) + }) + } +} + +func BenchmarkWriteToCacheWith1024ShardsAndSmallShardInitSize(b *testing.B) { + writeToCache(b, 1024, 100*time.Second, 100) +} + +func BenchmarkReadFromCacheNonExistentKeys(b *testing.B) { + for _, shards := range []int{1, 512, 1024, 8192} { + b.Run(fmt.Sprintf("%d-shards", shards), func(b *testing.B) { + readFromCacheNonExistentKeys(b, 1024) + }) + } +} + +func writeToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 500, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + cache.Set(fmt.Sprintf("key-%d-%d", id, counter), message) + counter = counter + 1 + } + }) +} + +func appendToCache(b *testing.B, shards int, lifeWindow time.Duration, requestsInLifeWindow int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: lifeWindow, + MaxEntriesInWindow: max(requestsInLifeWindow, 100), + MaxEntrySize: 2000, + }) + rand.Seed(time.Now().Unix()) + + b.RunParallel(func(pb *testing.PB) { + id := rand.Int() + counter := 0 + + b.ReportAllocs() + for pb.Next() { + key := fmt.Sprintf("key-%d-%d", id, counter) + for j := 0; j < 7; j++ { + cache.Append(key, message) + } + counter = counter + 1 + } + }) +} + +func readFromCache(b *testing.B, shards int, info bool) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + for i := 0; i < b.N; i++ { + cache.Set(strconv.Itoa(i), message) + } + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + if info { + cache.GetWithInfo(strconv.Itoa(rand.Intn(b.N))) + } else { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + } + }) +} + +func readFromCacheNonExistentKeys(b *testing.B, shards int) { + cache, _ := New(context.Background(), Config{ + Shards: shards, + LifeWindow: 1000 * time.Second, + MaxEntriesInWindow: max(b.N, 100), + MaxEntrySize: 500, + }) + b.ResetTimer() + + b.RunParallel(func(pb *testing.PB) { + b.ReportAllocs() + + for pb.Next() { + cache.Get(strconv.Itoa(rand.Intn(b.N))) + } + }) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/bigcache_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/bigcache_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2f86a6d6801f183e8628e1a9e5725c109e1d2d7e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/bigcache_test.go @@ -0,0 +1,1391 @@ +package bigcache + +import ( + "bytes" + "context" + "fmt" + "math" + "math/rand" + "runtime" + "strings" + "sync" + "testing" + "time" +) + +func TestWriteAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + value := []byte("value") + + // when + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestAppendAndGetOnCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(5*time.Second)) + key := "key" + value1 := make([]byte, 50) + rand.Read(value1) + value2 := make([]byte, 50) + rand.Read(value2) + value3 := make([]byte, 50) + rand.Read(value3) + + // when + _, err := cache.Get(key) + + // then + assertEqual(t, ErrEntryNotFound, err) + + // when + cache.Append(key, value1) + cachedValue, err := cache.Get(key) + + // then + noError(t, err) + assertEqual(t, value1, cachedValue) + + // when + cache.Append(key, value2) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue := value1 + expectedValue = append(expectedValue, value2...) + assertEqual(t, expectedValue, cachedValue) + + // when + cache.Append(key, value3) + cachedValue, err = cache.Get(key) + + // then + noError(t, err) + expectedValue = value1 + expectedValue = append(expectedValue, value2...) + expectedValue = append(expectedValue, value3...) + assertEqual(t, expectedValue, cachedValue) +} + +// TestAppendRandomly does simultaneous appends to check for corruption errors. +func TestAppendRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 1 * time.Second, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + StatsEnabled: true, + Verbose: true, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + Logger: DefaultLogger(), + } + cache, err := New(context.Background(), c) + noError(t, err) + + nKeys := 5 + nAppendsPerKey := 2000 + nWorker := 10 + var keys []string + for i := 0; i < nKeys; i++ { + for j := 0; j < nAppendsPerKey; j++ { + keys = append(keys, fmt.Sprintf("key%d", i)) + } + } + rand.Shuffle(len(keys), func(i, j int) { + keys[i], keys[j] = keys[j], keys[i] + }) + + jobs := make(chan string, len(keys)) + for _, key := range keys { + jobs <- key + } + close(jobs) + + var wg sync.WaitGroup + for i := 0; i < nWorker; i++ { + wg.Add(1) + go func() { + for { + key, ok := <-jobs + if !ok { + break + } + cache.Append(key, []byte(key)) + } + wg.Done() + }() + } + wg.Wait() + + assertEqual(t, nKeys, cache.Len()) + for i := 0; i < nKeys; i++ { + key := fmt.Sprintf("key%d", i) + expectedValue := []byte(strings.Repeat(key, nAppendsPerKey)) + cachedValue, err := cache.Get(key) + noError(t, err) + assertEqual(t, expectedValue, cachedValue) + } +} + +func TestAppendCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Append("a", []byte("1")) + cachedValue, err := cache.Get("a") + + //then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + + // when + err = cache.Append("b", []byte("2")) + + // then + noError(t, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + cachedValue, err = cache.Get("b") + noError(t, err) + assertEqual(t, []byte("2"), cachedValue) + +} + +func TestConstructCacheWithDefaultHasher(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + _, ok := cache.hash.(fnv64a) + assertEqual(t, true, ok) +} + +func TestNewBigcacheValidation(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + cfg Config + want string + }{ + { + cfg: Config{Shards: 18}, + want: "Shards number must be power of two", + }, + { + cfg: Config{Shards: 16, MaxEntriesInWindow: -1}, + want: "MaxEntriesInWindow must be >= 0", + }, + { + cfg: Config{Shards: 16, MaxEntrySize: -1}, + want: "MaxEntrySize must be >= 0", + }, + { + cfg: Config{Shards: 16, HardMaxCacheSize: -1}, + want: "HardMaxCacheSize must be >= 0", + }, + } { + t.Run(tc.want, func(t *testing.T) { + cache, error := New(context.Background(), tc.cfg) + + assertEqual(t, (*BigCache)(nil), cache) + assertEqual(t, tc.want, error.Error()) + }) + } +} + +func TestEntryNotFound(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + }) + + // when + _, err := cache.Get("nonExistingKey") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEviction(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + clock.set(1) + cache.Set("key2", []byte("value2")) + _, err := cache.Get("key") + + // then + noError(t, err) + + // when + clock.set(5) + cache.Set("key2", []byte("value2")) + _, err = cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) +} + +func TestTimingEvictionShouldEvictOnlyFromUpdatedShard(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value 2")) + value, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, []byte("value"), value) +} + +func TestCleanShouldEvictAll(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 4, + LifeWindow: time.Second, + CleanWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + cache.Set("key", []byte("value")) + <-time.After(3 * time.Second) + value, err := cache.Get("key") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, value, []byte(nil)) +} + +func TestOnRemoveCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemoveExtInvoked := false + onRemove := func(key string, entry []byte) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + } + onRemoveExt := func(key string, entry []byte, reason RemoveReason) { + onRemoveExtInvoked = true + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemove: onRemove, + OnRemoveWithReason: onRemoveExt, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) + assertEqual(t, false, onRemoveExtInvoked) +} + +func TestOnRemoveWithReasonCallback(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + assertEqual(t, "key", key) + assertEqual(t, []byte("value"), entry) + assertEqual(t, reason, RemoveReason(Expired)) + } + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilter(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveInvoked := false + onRemove := func(key string, entry []byte, reason RemoveReason) { + onRemoveInvoked = true + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key2", []byte("value2")) + + // then + assertEqual(t, false, onRemoveInvoked) + + // and when + cache.Delete("key2") + + // then + assertEqual(t, true, onRemoveInvoked) +} + +func TestOnRemoveFilterExpired(t *testing.T) { + // t.Parallel() + + // given + clock := mockedClock{value: 0} + onRemoveDeleted, onRemoveExpired := false, false + var err error + onRemove := func(key string, entry []byte, reason RemoveReason) { + switch reason { + + case Deleted: + onRemoveDeleted = true + case Expired: + onRemoveExpired = true + + } + } + c := Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + OnRemoveWithReason: onRemove, + } + + cache, err := newBigCache(context.Background(), c, &clock) + assertEqual(t, err, nil) + + // case 1: key is deleted AFTER expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key", []byte("value")) + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + + err = cache.Delete("key") + + // then + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, false, onRemoveDeleted) + assertEqual(t, true, onRemoveExpired) + + // case 1: key is deleted BEFORE expire + // when + onRemoveDeleted, onRemoveExpired = false, false + clock.set(0) + + cache.Set("key2", []byte("value2")) + err = cache.Delete("key2") + clock.set(5) + cache.cleanUp(uint64(clock.Epoch())) + // then + + assertEqual(t, err, nil) + assertEqual(t, true, onRemoveDeleted) + assertEqual(t, false, onRemoveExpired) +} + +func TestOnRemoveGetEntryStats(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + count := uint32(0) + onRemove := func(key string, entry []byte, keyMetadata Metadata) { + count = keyMetadata.RequestCount + } + c := Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + OnRemoveWithMetadata: onRemove, + StatsEnabled: true, + }.OnRemoveFilterSet(Deleted, NoSpace) + + cache, _ := newBigCache(context.Background(), c, &clock) + + // when + cache.Set("key", []byte("value")) + + for i := 0; i < 100; i++ { + cache.Get("key") + } + + cache.Delete("key") + + // then + assertEqual(t, uint32(100), count) +} + +func TestCacheLen(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestCacheCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + assertEqual(t, 40960, cache.Capacity()) +} + +func TestCacheInitialCapacity(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 2 * 1024, + HardMaxCacheSize: 1, + MaxEntrySize: 1024, + }) + + assertEqual(t, 0, cache.Len()) + assertEqual(t, 1024*1024, cache.Capacity()) + + keys := 1024 * 1024 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, true, cache.Len() < keys) + assertEqual(t, 1024*1024, cache.Capacity()) +} + +func TestRemoveEntriesWhenShardIsFull(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 100 * time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + }) + + value := blob('a', 1024*300) + + // when + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cache.Set("key", value) + cachedValue, err := cache.Get("key") + + // then + noError(t, err) + assertEqual(t, value, cachedValue) +} + +func TestCacheStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + // then + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) +} +func TestCacheEntryStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + StatsEnabled: true, + }) + + cache.Set("key0", []byte("value")) + + for i := 0; i < 10; i++ { + _, err := cache.Get("key0") + noError(t, err) + } + + // then + keyMetadata := cache.KeyMetadata("key0") + assertEqual(t, uint32(10), keyMetadata.RequestCount) +} + +func TestCacheRestStats(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + for i := 0; i < 100; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + for i := 0; i < 10; i++ { + value, err := cache.Get(fmt.Sprintf("key%d", i)) + noError(t, err) + assertEqual(t, string(value), "value") + } + for i := 100; i < 110; i++ { + _, err := cache.Get(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + for i := 10; i < 20; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + noError(t, err) + } + for i := 110; i < 120; i++ { + err := cache.Delete(fmt.Sprintf("key%d", i)) + assertEqual(t, ErrEntryNotFound, err) + } + + stats := cache.Stats() + assertEqual(t, stats.Hits, int64(10)) + assertEqual(t, stats.Misses, int64(10)) + assertEqual(t, stats.DelHits, int64(10)) + assertEqual(t, stats.DelMisses, int64(10)) + + //then + cache.ResetStats() + stats = cache.Stats() + assertEqual(t, stats.Hits, int64(0)) + assertEqual(t, stats.Misses, int64(0)) + assertEqual(t, stats.DelHits, int64(0)) + assertEqual(t, stats.DelMisses, int64(0)) +} + +func TestCacheDel(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), DefaultConfig(time.Second)) + + // when + err := cache.Delete("nonExistingKey") + + // then + assertEqual(t, err, ErrEntryNotFound) + + // and when + cache.Set("existingKey", nil) + err = cache.Delete("existingKey") + cachedValue, _ := cache.Get("existingKey") + + // then + noError(t, err) + assertEqual(t, 0, len(cachedValue)) +} + +// TestCacheDelRandomly does simultaneous deletes, puts and gets, to check for corruption errors. +func TestCacheDelRandomly(t *testing.T) { + t.Parallel() + + c := Config{ + Shards: 1, + LifeWindow: time.Second, + CleanWindow: 0, + MaxEntriesInWindow: 10, + MaxEntrySize: 10, + Verbose: false, + Hasher: newDefaultHasher(), + HardMaxCacheSize: 1, + StatsEnabled: true, + Logger: DefaultLogger(), + } + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + var ntest = 800000 + wg.Add(3) + go func() { + for i := 0; i < ntest; i++ { + r := uint8(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + cache.Delete(key) + } + wg.Done() + }() + valueLen := 1024 + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + cache.Set(key, val) + } + wg.Done() + }() + go func() { + val := make([]byte, valueLen) + for i := 0; i < ntest; i++ { + r := byte(rand.Int()) + key := fmt.Sprintf("thekey%d", r) + + for j := 0; j < len(val); j++ { + val[j] = r + } + if got, err := cache.Get(key); err == nil && !bytes.Equal(got, val) { + t.Errorf("got %s ->\n %x\n expected:\n %x\n ", key, got, val) + } + } + wg.Done() + }() + wg.Wait() +} + +func TestWriteAndReadParallelSameKeyWithStats(t *testing.T) { + t.Parallel() + + c := DefaultConfig(10 * time.Second) + c.StatsEnabled = true + + cache, _ := New(context.Background(), c) + var wg sync.WaitGroup + ntest := 1000 + n := 10 + wg.Add(n) + key := "key" + value := blob('a', 1024) + for i := 0; i < ntest; i++ { + assertEqual(t, nil, cache.Set(key, value)) + } + for j := 0; j < n; j++ { + go func() { + for i := 0; i < ntest; i++ { + v, err := cache.Get(key) + assertEqual(t, nil, err) + assertEqual(t, value, v) + } + wg.Done() + }() + } + + wg.Wait() + + assertEqual(t, Stats{Hits: int64(n * ntest)}, cache.Stats()) + assertEqual(t, ntest*n, int(cache.KeyMetadata(key).RequestCount)) +} + +func TestCacheReset(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) + + // and when + cache.Reset() + + // then + assertEqual(t, 0, cache.Len()) + + // and when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + // then + assertEqual(t, keys, cache.Len()) +} + +func TestIterateOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + cache.Reset() + + // then + iterator := cache.Iterator() + + assertEqual(t, false, iterator.SetNext()) +} + +func TestGetOnResetCache(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + keys := 1337 + + // when + for i := 0; i < keys; i++ { + cache.Set(fmt.Sprintf("key%d", i), []byte("value")) + } + + cache.Reset() + + // then + value, err := cache.Get("key1") + + assertEqual(t, err, ErrEntryNotFound) + assertEqual(t, value, []byte(nil)) +} + +func TestEntryUpdate(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + // when + cache.Set("key", []byte("value")) + clock.set(5) + cache.Set("key", []byte("value2")) + clock.set(7) + cache.Set("key2", []byte("value3")) + cachedValue, _ := cache.Get("key") + + // then + assertEqual(t, []byte("value2"), cachedValue) +} + +func TestOldestEntryDeletionWhenMaxCacheSizeIsReached(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("key1", blob('a', 1024*400)) + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*800)) + + _, key1Err := cache.Get("key1") + _, key2Err := cache.Get("key2") + entry3, _ := cache.Get("key3") + + // then + assertEqual(t, key1Err, ErrEntryNotFound) + assertEqual(t, key2Err, ErrEntryNotFound) + assertEqual(t, blob('c', 1024*800), entry3) +} + +func TestRetrievingEntryShouldCopy(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + cache.Set("key1", blob('a', 1024*400)) + value, key1Err := cache.Get("key1") + + // when + // override queue + cache.Set("key2", blob('b', 1024*400)) + cache.Set("key3", blob('c', 1024*400)) + cache.Set("key4", blob('d', 1024*400)) + cache.Set("key5", blob('d', 1024*400)) + + // then + noError(t, key1Err) + assertEqual(t, blob('a', 1024*400), value) +} + +func TestEntryBiggerThanMaxShardSizeError(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + err := cache.Set("key1", blob('a', 1024*1025)) + + // then + assertEqual(t, "entry is bigger than max shard size", err.Error()) +} + +func TestHashCollision(t *testing.T) { + t.Parallel() + + ml := &mockedLogger{} + // given + cache, _ := New(context.Background(), Config{ + Shards: 16, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + Logger: ml, + }) + + // when + cache.Set("liquid", []byte("value")) + cachedValue, err := cache.Get("liquid") + + // then + noError(t, err) + assertEqual(t, []byte("value"), cachedValue) + + // when + cache.Set("costarring", []byte("value 2")) + cachedValue, err = cache.Get("costarring") + + // then + noError(t, err) + assertEqual(t, []byte("value 2"), cachedValue) + + // when + cachedValue, err = cache.Get("liquid") + + // then + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, []byte(nil), cachedValue) + + assertEqual(t, "Collision detected. Both %q and %q have the same hash %x", ml.lastFormat) + assertEqual(t, cache.Stats().Collisions, int64(1)) +} + +func TestNilValueCaching(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }) + + // when + cache.Set("Kierkegaard", []byte{}) + cachedValue, err := cache.Get("Kierkegaard") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Sartre", nil) + cachedValue, err = cache.Get("Sartre") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) + + // when + cache.Set("Nietzsche", []byte(nil)) + cachedValue, err = cache.Get("Nietzsche") + + // then + noError(t, err) + assertEqual(t, []byte{}, cachedValue) +} + +func TestClosing(t *testing.T) { + // given + config := Config{ + CleanWindow: time.Minute, + Shards: 1, + LifeWindow: 1 * time.Second, + } + startGR := runtime.NumGoroutine() + + // when + for i := 0; i < 100; i++ { + cache, _ := New(context.Background(), config) + cache.Close() + } + + // wait till all goroutines are stopped. + time.Sleep(200 * time.Millisecond) + + // then + endGR := runtime.NumGoroutine() + assertEqual(t, true, endGR >= startGR) + assertEqual(t, true, math.Abs(float64(endGR-startGR)) < 25) +} + +func TestEntryNotPresent(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + }, &clock) + + // when + value, resp, err := cache.GetWithInfo("blah") + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, resp.EntryStatus, RemoveReason(0)) + assertEqual(t, cache.Stats().Misses, int64(1)) + assertEqual(t, []byte(nil), value) +} + +func TestBigCache_GetWithInfo(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + CleanWindow: 5 * time.Minute, + MaxEntriesInWindow: 1, + MaxEntrySize: 1, + HardMaxCacheSize: 1, + Verbose: true, + }, &clock) + key := "deadEntryKey" + value := "100" + cache.Set(key, []byte(value)) + + for _, tc := range []struct { + name string + clock int64 + wantData string + wantResp Response + }{ + { + name: "zero", + clock: 0, + wantData: value, + wantResp: Response{}, + }, + { + name: "Before Expired", + clock: 4, + wantData: value, + wantResp: Response{}, + }, + { + name: "Expired", + clock: 5, + wantData: value, + wantResp: Response{}, + }, + { + name: "After Expired", + clock: 6, + wantData: value, + wantResp: Response{EntryStatus: Expired}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + clock.set(tc.clock) + data, resp, err := cache.GetWithInfo(key) + + assertEqual(t, []byte(tc.wantData), data) + noError(t, err) + assertEqual(t, tc.wantResp, resp) + }) + } +} + +func TestBigCache_GetWithInfoCollision(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: 5 * time.Second, + MaxEntriesInWindow: 10, + MaxEntrySize: 256, + Verbose: true, + Hasher: hashStub(5), + }) + + //when + cache.Set("a", []byte("1")) + cachedValue, resp, err := cache.GetWithInfo("a") + + // then + noError(t, err) + assertEqual(t, []byte("1"), cachedValue) + assertEqual(t, Response{}, resp) + + // when + cachedValue, resp, err = cache.GetWithInfo("b") + + // then + assertEqual(t, []byte(nil), cachedValue) + assertEqual(t, Response{}, resp) + assertEqual(t, ErrEntryNotFound, err) + assertEqual(t, cache.Stats().Collisions, int64(1)) + +} + +type mockedLogger struct { + lastFormat string + lastArgs []interface{} +} + +func (ml *mockedLogger) Printf(format string, v ...interface{}) { + ml.lastFormat = format + ml.lastArgs = v +} + +type mockedClock struct { + value int64 +} + +func (mc *mockedClock) Epoch() int64 { + return mc.value +} + +func (mc *mockedClock) set(value int64) { + mc.value = value +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func TestCache_SetWithoutCleanWindow(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.CleanWindow = 0 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } +} + +func TestCache_RepeatedSetWithBiggerEntry(t *testing.T) { + + opt := DefaultConfig(time.Second) + opt.Shards = 2 << 10 + opt.MaxEntriesInWindow = 1024 + opt.MaxEntrySize = 1 + opt.HardMaxCacheSize = 1 + bc, _ := New(context.Background(), opt) + + err := bc.Set("2225", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + err = bc.Set("8573", make([]byte, 100)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 450)) + if nil != err { + // occur error but go next + t.Logf("%v", err) + } + + err = bc.Set("7327", make([]byte, 300)) + if nil != err { + t.Error(err) + t.FailNow() + } + + err = bc.Set("8573", make([]byte, 200)) + if nil != err { + t.Error(err) + t.FailNow() + } + +} + +// TestBigCache_allocateAdditionalMemoryLeadPanic +// The new commit 16df11e change the encoding method,it can fix issue #300 +func TestBigCache_allocateAdditionalMemoryLeadPanic(t *testing.T) { + t.Parallel() + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 1, + LifeWindow: 3 * time.Second, + MaxEntrySize: 52, + }, &clock) + ts := time.Now().Unix() + clock.set(ts) + cache.Set("a", blob(0xff, 235)) + ts += 2 + clock.set(ts) + cache.Set("b", blob(0xff, 235)) + // expire the key "a" + ts += 2 + clock.set(ts) + // move tail to leftMargin,insert before head + cache.Set("c", blob(0xff, 108)) + // reallocate memory,fill the tail to head with zero byte,move head to leftMargin + cache.Set("d", blob(0xff, 1024)) + ts += 4 + clock.set(ts) + // expire the key "c" + cache.Set("e", blob(0xff, 3)) + // expire the zero bytes + cache.Set("f", blob(0xff, 3)) + // expire the key "b" + cache.Set("g", blob(0xff, 3)) + _, err := cache.Get("b") + assertEqual(t, err, ErrEntryNotFound) + data, _ := cache.Get("g") + assertEqual(t, []byte{0xff, 0xff, 0xff}, data) +} + +func TestRemoveNonExpiredData(t *testing.T) { + onRemove := func(key string, entry []byte, reason RemoveReason) { + if reason != Deleted { + if reason == Expired { + t.Errorf("[%d]Expired OnRemove [%s]\n", reason, key) + t.FailNow() + } else { + time.Sleep(time.Second) + } + } + } + + config := DefaultConfig(10 * time.Minute) + config.HardMaxCacheSize = 1 + config.MaxEntrySize = 1024 + config.MaxEntriesInWindow = 1024 + config.OnRemoveWithReason = onRemove + cache, err := New(context.Background(), config) + noError(t, err) + defer func() { + err := cache.Close() + noError(t, err) + }() + + data := func(l int) []byte { + m := make([]byte, l) + _, err := rand.Read(m) + noError(t, err) + return m + } + + for i := 0; i < 50; i++ { + key := fmt.Sprintf("key_%d", i) + //key := "key1" + err := cache.Set(key, data(800)) + noError(t, err) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/encoding_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/encoding_test.go new file mode 100644 index 0000000000000000000000000000000000000000..626386b165d0c39da022b9b7f268235bad55bea2 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/encoding_test.go @@ -0,0 +1,44 @@ +package bigcache + +import ( + "testing" + "time" +) + +func TestEncodeDecode(t *testing.T) { + // given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "key" + data := []byte("data") + buffer := make([]byte, 100) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 100, len(buffer)) +} + +func TestAllocateBiggerBuffer(t *testing.T) { + //given + now := uint64(time.Now().Unix()) + hash := uint64(42) + key := "1" + data := []byte("2") + buffer := make([]byte, 1) + + // when + wrapped := wrapEntry(now, hash, key, data, &buffer) + + // then + assertEqual(t, key, readKeyFromEntry(wrapped)) + assertEqual(t, hash, readHashFromEntry(wrapped)) + assertEqual(t, now, readTimestampFromEntry(wrapped)) + assertEqual(t, data, readEntry(wrapped)) + assertEqual(t, 2+headersSizeInBytes, len(buffer)) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/examples_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/examples_test.go new file mode 100644 index 0000000000000000000000000000000000000000..36fc76c67a934203fc8715d9a8ea6bd9b916a2d4 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/examples_test.go @@ -0,0 +1,79 @@ +package bigcache_test + +import ( + "context" + "fmt" + "log" + "time" + + "github.com/allegro/bigcache/v3" +) + +func Example() { + cache, _ := bigcache.New(context.Background(), bigcache.DefaultConfig(10*time.Minute)) + + cache.Set("my-unique-key", []byte("value")) + + entry, _ := cache.Get("my-unique-key") + fmt.Println(string(entry)) + // Output: value +} + +func Example_custom() { + // When cache load can be predicted in advance then it is better to use custom initialization + // because additional memory allocation can be avoided in that way. + config := bigcache.Config{ + // number of shards (must be a power of 2) + Shards: 1024, + + // time after which entry can be evicted + LifeWindow: 10 * time.Minute, + + // Interval between removing expired entries (clean up). + // If set to <= 0 then no action is performed. + // Setting to < 1 second is counterproductive — bigcache has a one second resolution. + CleanWindow: 5 * time.Minute, + + // rps * lifeWindow, used only in initial memory allocation + MaxEntriesInWindow: 1000 * 10 * 60, + + // max entry size in bytes, used only in initial memory allocation + MaxEntrySize: 500, + + // prints information about additional memory allocation + Verbose: true, + + // cache will not allocate more memory than this limit, value in MB + // if value is reached then the oldest entries can be overridden for the new ones + // 0 value means no size limit + HardMaxCacheSize: 8192, + + // callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A bitmask representing the reason will be returned. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + OnRemove: nil, + + // OnRemoveWithReason is a callback fired when the oldest entry is removed because of its expiration time or no space left + // for the new entry, or because delete was called. A constant representing the reason will be passed through. + // Default value is nil which means no callback and it prevents from unwrapping the oldest entry. + // Ignored if OnRemove is specified. + OnRemoveWithReason: nil, + } + + cache, initErr := bigcache.New(context.Background(), config) + if initErr != nil { + log.Fatal(initErr) + } + + err := cache.Set("my-unique-key", []byte("value")) + if err != nil { + log.Fatal(err) + } + + entry, err := cache.Get("my-unique-key") + if err != nil { + log.Fatal(err) + } + fmt.Println(string(entry)) + // Output: value +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/fnv_bench_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/fnv_bench_test.go new file mode 100644 index 0000000000000000000000000000000000000000..327cf32f8deb79a7f1140ea19655e6f39356af50 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/fnv_bench_test.go @@ -0,0 +1,18 @@ +package bigcache + +import "testing" + +var text = "abcdefg" + +func BenchmarkFnvHashSum64(b *testing.B) { + h := newDefaultHasher() + for i := 0; i < b.N; i++ { + h.Sum64(text) + } +} + +func BenchmarkFnvHashStdLibSum64(b *testing.B) { + for i := 0; i < b.N; i++ { + stdLibFnvSum64(text) + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/fnv_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/fnv_test.go new file mode 100644 index 0000000000000000000000000000000000000000..c94c074662371d9ad5626b49208f2e29ead29dfc --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/fnv_test.go @@ -0,0 +1,35 @@ +package bigcache + +import ( + "hash/fnv" + "testing" +) + +type testCase struct { + text string + expectedHash uint64 +} + +var testCases = []testCase{ + {"", stdLibFnvSum64("")}, + {"a", stdLibFnvSum64("a")}, + {"ab", stdLibFnvSum64("ab")}, + {"abc", stdLibFnvSum64("abc")}, + {"some longer and more complicated text", stdLibFnvSum64("some longer and more complicated text")}, +} + +func TestFnvHashSum64(t *testing.T) { + h := newDefaultHasher() + for _, testCase := range testCases { + hashed := h.Sum64(testCase.text) + if hashed != testCase.expectedHash { + t.Errorf("hash(%q) = %d want %d", testCase.text, hashed, testCase.expectedHash) + } + } +} + +func stdLibFnvSum64(key string) uint64 { + h := fnv.New64a() + h.Write([]byte(key)) + return h.Sum64() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/hash_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/hash_test.go new file mode 100644 index 0000000000000000000000000000000000000000..2252e7fb95b4181300f59f9c98aa03d64d1e7a59 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/hash_test.go @@ -0,0 +1,7 @@ +package bigcache + +type hashStub uint64 + +func (stub hashStub) Sum64(_ string) uint64 { + return uint64(stub) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/iterator_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/iterator_test.go new file mode 100644 index 0000000000000000000000000000000000000000..7f1af2bbbc28f0d46486b188a9e4e1d3caa4acc8 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/iterator_test.go @@ -0,0 +1,268 @@ +package bigcache + +import ( + "context" + "fmt" + "math/rand" + "runtime" + "strconv" + "sync" + "testing" + "time" +) + +func TestEntriesIterator(t *testing.T) { + t.Parallel() + + // given + keysCount := 1000 + cache, _ := New(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + value := []byte("value") + + for i := 0; i < keysCount; i++ { + cache.Set(fmt.Sprintf("key%d", i), value) + } + + // when + keys := make(map[string]struct{}) + iterator := cache.Iterator() + + for iterator.SetNext() { + current, err := iterator.Value() + + if err == nil { + keys[current.Key()] = struct{}{} + } + } + + // then + assertEqual(t, keysCount, len(keys)) +} + +func TestEntriesIteratorWithMostShardsEmpty(t *testing.T) { + t.Parallel() + + // given + clock := mockedClock{value: 0} + cache, _ := newBigCache(context.Background(), Config{ + Shards: 8, + LifeWindow: 6 * time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }, &clock) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + current, err := iterator.Value() + + // then + noError(t, err) + assertEqual(t, "key", current.Key()) + assertEqual(t, uint64(0x3dc94a19365b10ec), current.Hash()) + assertEqual(t, []byte("value"), current.Value()) + assertEqual(t, uint64(0), current.Timestamp()) +} + +func TestEntriesIteratorWithConcurrentUpdate(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + cache.Set("key", []byte("value")) + + // when + iterator := cache.Iterator() + + // then + if !iterator.SetNext() { + t.Errorf("Iterator should contain at least single element") + } + + getOldestEntry := func(s *cacheShard) ([]byte, error) { + s.lock.RLock() + defer s.lock.RUnlock() + return s.entries.Peek() + } + + // Quite ugly but works + for i := 0; i < cache.config.Shards; i++ { + if oldestEntry, err := getOldestEntry(cache.shards[i]); err == nil { + cache.onEvict(oldestEntry, 10, cache.shards[i].removeOldestEntry) + } + } + + current, err := iterator.Value() + assertEqual(t, nil, err) + assertEqual(t, []byte("value"), current.Value()) + + next := iterator.SetNext() + assertEqual(t, false, next) +} + +func TestEntriesIteratorWithAllShardsEmpty(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + if iterator.SetNext() { + t.Errorf("Iterator should not contain any elements") + } +} + +func TestEntriesIteratorInInvalidState(t *testing.T) { + t.Parallel() + + // given + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 1, + MaxEntrySize: 256, + }) + + // when + iterator := cache.Iterator() + + // then + _, err := iterator.Value() + assertEqual(t, ErrInvalidIteratorState, err) + assertEqual(t, "Iterator is in invalid state. Use SetNext() to move to next position", err.Error()) +} + +func TestEntriesIteratorParallelAdd(t *testing.T) { + bc, err := New(context.Background(), DefaultConfig(1*time.Minute)) + if err != nil { + panic(err) + } + + wg := sync.WaitGroup{} + wg.Add(1) + go func() { + for i := 0; i < 10000; i++ { + err := bc.Set(strconv.Itoa(i), []byte("aaaaaaa")) + if err != nil { + panic(err) + } + + runtime.Gosched() + } + wg.Done() + }() + + for i := 0; i < 100; i++ { + iter := bc.Iterator() + for iter.SetNext() { + _, _ = iter.Value() + } + } + wg.Wait() +} + +func TestParallelSetAndIteration(t *testing.T) { + t.Parallel() + + rand.Seed(0) + + cache, _ := New(context.Background(), Config{ + Shards: 1, + LifeWindow: time.Second, + MaxEntriesInWindow: 100, + MaxEntrySize: 256, + HardMaxCacheSize: 1, + Verbose: true, + }) + + entrySize := 1024 * 100 + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + + wg := sync.WaitGroup{} + wg.Add(2) + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, err, nil) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + err := cache.Set(strconv.Itoa(rand.Intn(100)), blob('a', entrySize)) + noError(t, err) + } + } + }() + + go func() { + defer func() { + err := recover() + // no panic + assertEqual(t, nil, err) + }() + + defer wg.Done() + + isTimeout := false + + for { + if isTimeout { + break + } + select { + case <-ctx.Done(): + isTimeout = true + default: + iter := cache.Iterator() + for iter.SetNext() { + entry, err := iter.Value() + + // then + noError(t, err) + assertEqual(t, entrySize, len(entry.Value())) + } + } + } + }() + + wg.Wait() +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/queue/bytes_queue_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/queue/bytes_queue_test.go new file mode 100644 index 0000000000000000000000000000000000000000..81dd107857627e2c7adaa086ea68d8be17201f6e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/queue/bytes_queue_test.go @@ -0,0 +1,510 @@ +package queue + +import ( + "bytes" + "fmt" + "path" + "reflect" + "runtime" + "testing" +) + +func TestPushAndPop(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 0, true) + entry := []byte("hello") + + // when + _, err := queue.Pop() + + // then + assertEqual(t, "Empty queue", err.Error()) + + // when + queue.Push(entry) + + // then + assertEqual(t, entry, pop(queue)) +} + +func TestLen(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + assertEqual(t, 0, queue.Len()) + + // when + queue.Push(entry) + + // then + assertEqual(t, queue.Len(), 1) +} + +func TestPeek(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + read, err := queue.Peek() + err2 := queue.peekCheckErr(queue.head) + // then + assertEqual(t, err, err2) + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + err2 = queue.peekCheckErr(queue.head) + + // then + assertEqual(t, err, err2) + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) +} + +func TestResetFullQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(10, 20, false) + + // when + queue.Push(blob('a', 3)) + queue.Push(blob('b', 4)) + + // when + assertEqual(t, blob('a', 3), pop(queue)) // space freed at the beginning + _, err := queue.Push(blob('a', 3)) // will set q.full to true + + // then + assertEqual(t, err, nil) + + // when + queue.Reset() + queue.Push(blob('c', 8)) // should not trigger a re-allocation + + // then + assertEqual(t, blob('c', 8), pop(queue)) + assertEqual(t, queue.Capacity(), 10) +} + +func TestReset(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + entry := []byte("hello") + + // when + queue.Push(entry) + queue.Push(entry) + queue.Push(entry) + + queue.Reset() + read, err := queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) + + // when + queue.Push(entry) + read, err = queue.Peek() + + // then + noError(t, err) + assertEqual(t, pop(queue), read) + assertEqual(t, entry, read) + + // when + read, err = queue.Peek() + + // then + assertEqual(t, "Empty queue", err.Error()) + assertEqual(t, 0, len(read)) +} + +func TestReuseAvailableSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) + queue.Push(blob('b', 20)) + queue.Pop() + queue.Push(blob('c', 20)) + + // then + assertEqual(t, 100, queue.Capacity()) + assertEqual(t, blob('b', 20), pop(queue)) +} + +func TestAllocateAdditionalSpace(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push([]byte("hello1")) + queue.Push([]byte("hello2")) + + // then + assertEqual(t, 22, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + queue.Push(blob('c', 6)) // 7 bytes needed, 13 bytes available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), pop(queue)) + assertEqual(t, blob('c', 6), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(25, 0, false) + + // when + queue.Push(blob('a', 3)) // header + entry + left margin = 5 bytes + index, _ := queue.Push(blob('b', 6)) // additional 7 bytes + queue.Pop() // space freed, 4 bytes available at the beginning + newestIndex, _ := queue.Push(blob('c', 6)) // 7 bytes needed, 13 available at the tail + + // then + assertEqual(t, 25, queue.Capacity()) + assertEqual(t, blob('b', 6), get(queue, index)) + assertEqual(t, blob('c', 6), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('c', 30), pop(queue)) + // empty blob fills space between tail and head, + // created when additional memory was allocated, + // it keeps current entries indexes unchanged + assertEqual(t, blob(0, 39), pop(queue)) + assertEqual(t, blob('b', 10), pop(queue)) + assertEqual(t, blob('d', 40), pop(queue)) +} + +func TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(200, 0, false) + + // when + queue.Push(blob('a', 30)) // header + entry + left margin = 32 bytes + queue.Push(blob('b', 1)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('b', 125)) // 32 + 128 + 1 = 161 bytes + queue.Push(blob('c', 20)) // 160 + 20 + 1 = 182 + queue.Pop() // space freed at the beginning + queue.Pop() // free 2 bytes + queue.Pop() // free 126 + queue.Push(blob('d', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer, now free space is 128 bytes + queue.Push(blob('e', 160)) // invoke allocateAdditionalMemory but fill 127 bytes free space (It should be 128 bytes, but 127 are filled, leaving one byte unfilled) + + // then + assertEqual(t, 400, queue.Capacity()) + assertEqual(t, blob('d', 30), pop(queue)) + assertEqual(t, blob(0, 126), pop(queue)) //126 bytes data with 2bytes header only possible as empty entry + assertEqual(t, blob('c', 20), pop(queue)) //The data is not expected + assertEqual(t, blob('e', 160), pop(queue)) +} + +func TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(100, 0, false) + + // when + queue.Push(blob('a', 70)) // header + entry + left margin = 72 bytes + index, _ := queue.Push(blob('b', 10)) // 72 + 10 + 1 = 83 bytes + queue.Pop() // space freed at the beginning + queue.Push(blob('c', 30)) // 31 bytes used at the beginning, tail pointer is before head pointer + newestIndex, _ := queue.Push(blob('d', 40)) // 41 bytes needed but no available in one segment, allocate new memory + + // then + assertEqual(t, 200, queue.Capacity()) + assertEqual(t, blob('b', 10), get(queue, index)) + assertEqual(t, blob('d', 40), get(queue, newestIndex)) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanInitQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(11, 0, false) + + // when + queue.Push(blob('a', 100)) + // then + assertEqual(t, blob('a', 100), pop(queue)) + // 224 = (101 + 11) * 2 + assertEqual(t, 224, queue.Capacity()) +} + +func TestAllocateAdditionalSpaceForValueBiggerThanQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(21, 0, false) + + // when + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 2)) + queue.Push(make([]byte, 100)) + + // then + queue.Pop() + queue.Pop() + assertEqual(t, make([]byte, 100), pop(queue)) + // 244 = (101 + 21) * 2 + assertEqual(t, 244, queue.Capacity()) +} + +func TestPopWholeQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + queue.Push([]byte("a")) + queue.Push([]byte("b")) + queue.Pop() + queue.Pop() + queue.Push([]byte("c")) + + // then + assertEqual(t, 13, queue.Capacity()) + assertEqual(t, []byte("c"), pop(queue)) +} + +func TestGetEntryFromIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(20, 0, false) + + // when + queue.Push([]byte("a")) + index, _ := queue.Push([]byte("b")) + queue.Push([]byte("c")) + result, _ := queue.Get(index) + + // then + assertEqual(t, []byte("b"), result) +} + +func TestGetEntryFromInvalidIndex(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(0) + err2 := queue.CheckGet(0) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index must be greater than zero. Invalid index.", err.Error()) +} + +func TestGetEntryFromIndexOutOfRange(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(1, 0, false) + queue.Push([]byte("a")) + + // when + result, err := queue.Get(42) + err2 := queue.CheckGet(42) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Index out of range", err.Error()) +} + +func TestGetEntryFromEmptyQueue(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(13, 0, false) + + // when + result, err := queue.Get(1) + err2 := queue.CheckGet(1) + + // then + assertEqual(t, err, err2) + assertEqual(t, []byte(nil), result) + assertEqual(t, "Empty queue", err.Error()) +} + +func TestMaxSizeLimit(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(30, 50, false) + + // when + queue.Push(blob('a', 25)) + queue.Push(blob('b', 5)) + capacity := queue.Capacity() + _, err := queue.Push(blob('c', 20)) + + // then + assertEqual(t, 50, capacity) + assertEqual(t, "Full queue. Maximum size limit reached.", err.Error()) + assertEqual(t, blob('a', 25), pop(queue)) + assertEqual(t, blob('b', 5), pop(queue)) +} + +func TestPushEntryAfterAllocateAdditionMemory(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 20, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + queue.Pop() + + // allocate more memory + assertEqual(t, 9, queue.Capacity()) + queue.Push([]byte("c")) + assertEqual(t, 18, queue.Capacity()) + + // push after allocate + _, err := queue.Push([]byte("d")) + noError(t, err) +} + +func TestPushEntryAfterAllocateAdditionMemoryInFull(t *testing.T) { + t.Parallel() + + // given + queue := NewBytesQueue(9, 40, true) + + // when + queue.Push([]byte("aaa")) + queue.Push([]byte("bb")) + _, err := queue.Pop() + noError(t, err) + + queue.Push([]byte("c")) + queue.Push([]byte("d")) + queue.Push([]byte("e")) + _, err = queue.Pop() + noError(t, err) + _, err = queue.Pop() + noError(t, err) + queue.Push([]byte("fff")) + _, err = queue.Pop() + noError(t, err) +} + +func pop(queue *BytesQueue) []byte { + entry, err := queue.Pop() + if err != nil { + panic(err) + } + return entry +} + +func get(queue *BytesQueue, index int) []byte { + entry, err := queue.Get(index) + if err != nil { + panic(err) + } + return entry +} + +func blob(char byte, len int) []byte { + return bytes.Repeat([]byte{char}, len) +} + +func assertEqual(t *testing.T, expected, actual interface{}, msgAndArgs ...interface{}) { + if !objectsAreEqual(expected, actual) { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Not equal: \n"+ + "expected: %T(%#v)\n"+ + "actual : %T(%#v)\n", + file, line, expected, expected, actual, actual), msgAndArgs...) + } +} + +func noError(t *testing.T, e error) { + if e != nil { + _, file, line, _ := runtime.Caller(1) + file = path.Base(file) + t.Errorf(fmt.Sprintf("\n%s:%d: Error is not nil: \n"+ + "actual : %T(%#v)\n", file, line, e, e)) + } +} + +func objectsAreEqual(expected, actual interface{}) bool { + if expected == nil || actual == nil { + return expected == actual + } + + exp, ok := expected.([]byte) + if !ok { + return reflect.DeepEqual(expected, actual) + } + + act, ok := actual.([]byte) + if !ok { + return false + } + if exp == nil || act == nil { + return exp == nil && act == nil + } + return bytes.Equal(exp, act) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/server/middleware_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/server/middleware_test.go new file mode 100644 index 0000000000000000000000000000000000000000..692141df02ddc7f331231862196d339a1b9d0210 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/server/middleware_test.go @@ -0,0 +1,47 @@ +package main + +import ( + "bytes" + "log" + "net/http" + "net/http/httptest" + "testing" +) + +func emptyTestHandler() service { + return func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusAccepted) + }) + } +} + +func TestServiceLoader(t *testing.T) { + req, err := http.NewRequest("GET", "/api/v1/stats", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), emptyTestHandler()) + testHandlers.ServeHTTP(rr, req) + if status := rr.Code; status != http.StatusAccepted { + t.Errorf("handlers not loading properly. want: 202, got: %d", rr.Code) + } +} + +func TestRequestMetrics(t *testing.T) { + var b bytes.Buffer + logger := log.New(&b, "", log.LstdFlags) + req, err := http.NewRequest("GET", "/api/v1/cache/empty", nil) + if err != nil { + t.Error(err) + } + rr := httptest.NewRecorder() + testHandlers := serviceLoader(cacheIndexHandler(), requestMetrics(logger)) + testHandlers.ServeHTTP(rr, req) + targetTestString := b.String() + if len(targetTestString) == 0 { + t.Errorf("we are not logging request length strings.") + } + t.Log(targetTestString) +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/server/server_test.go b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/server/server_test.go new file mode 100644 index 0000000000000000000000000000000000000000..266afef7262d10e16f6f21b55255c085e89f6d3e --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/frozen/server/server_test.go @@ -0,0 +1,306 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http/httptest" + "testing" + "time" + + "github.com/allegro/bigcache/v3" +) + +const ( + testBaseString = "http://bigcache.org" +) + +func testCacheSetup() { + cache, _ = bigcache.New(context.Background(), bigcache.Config{ + Shards: 1024, + LifeWindow: 10 * time.Minute, + MaxEntriesInWindow: 1000 * 10 * 60, + MaxEntrySize: 500, + Verbose: true, + HardMaxCacheSize: 8192, + OnRemove: nil, + }) +} + +func TestMain(m *testing.M) { + testCacheSetup() + m.Run() +} + +func TestGetWithNoKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d", resp.StatusCode) + } +} + +func TestGetWithMissingKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/doesNotExist", nil) + rr := httptest.NewRecorder() + + getCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d", resp.StatusCode) + } +} + +func TestGetKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/getKey", nil) + rr := httptest.NewRecorder() + + // set something. + cache.Set("getKey", []byte("123")) + + getCacheHandler(rr, req) + resp := rr.Result() + + body, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } + + if string(body) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get existing key getKey.", string(body)) + } +} + +func TestPutKey(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + + testPutKeyResult, err := cache.Get("putKey") + if err != nil { + t.Errorf("error returning cache entry: %s", err) + } + + if string(testPutKeyResult) != "123" { + t.Errorf("want: 123; got: %s.\n\tcan't get PUT key putKey.", string(testPutKeyResult)) + } +} + +func TestPutEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 400 { + t.Errorf("want: 400; got: %d.\n\tempty key insertion should return with 400", resp.StatusCode) + } +} + +func TestDeleteEmptyKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete empty keys.", resp.StatusCode) + } +} + +func TestDeleteInvalidKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/invalidDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 404 { + t.Errorf("want: 404; got: %d.\n\tapparently we're trying to delete invalid keys.", resp.StatusCode) + } +} + +func TestDeleteKey(t *testing.T) { + t.Parallel() + + req := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testDeleteKey", bytes.NewBuffer([]byte("123"))) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + deleteCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestClearCache(t *testing.T) { + t.Parallel() + + putRequest := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer([]byte("123"))) + putResponseRecorder := httptest.NewRecorder() + + putCacheHandler(putResponseRecorder, putRequest) + + requestClear := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/clear", nil) + rr := httptest.NewRecorder() + + if err := cache.Set("testDeleteKey", []byte("123")); err != nil { + t.Errorf("can't set key for testing. %s", err) + } + + clearCache(rr, requestClear) + resp := rr.Result() + + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} +func TestGetStats(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + req := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + getCacheStatsHandler(rr, req) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } +} + +func TestGetStatsIndex(t *testing.T) { + t.Parallel() + var testStats bigcache.Stats + + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/stats", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/stats", nil) + rr := httptest.NewRecorder() + + // manually enter a key so there are some stats. get it so there's at least 1 hit. + if err := cache.Set("incrementStats", []byte("123")); err != nil { + t.Errorf("error setting cache value. error %s", err) + } + // it's okay if this fails, since we'll catch it downstream. + if _, err := cache.Get("incrementStats"); err != nil { + t.Errorf("can't find incrementStats. error: %s", err) + } + + testHandlers := statsIndexHandler() + testHandlers.ServeHTTP(rr, getreq) + resp := rr.Result() + + if err := json.NewDecoder(resp.Body).Decode(&testStats); err != nil { + t.Errorf("error decoding cache stats. error: %s", err) + } + + if testStats.Hits == 0 { + t.Errorf("want: > 0; got: 0.\n\thandler not properly returning stats info.") + } + + testHandlers = statsIndexHandler() + testHandlers.ServeHTTP(rr, putreq) + resp = rr.Result() + _, err := io.ReadAll(resp.Body) + if err != nil { + t.Errorf("cannot deserialise test response: %s", err) + } +} + +func TestCacheIndexHandler(t *testing.T) { + getreq := httptest.NewRequest("GET", testBaseString+"/api/v1/cache/testkey", nil) + putreq := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + delreq := httptest.NewRequest("DELETE", testBaseString+"/api/v1/cache/testkey", bytes.NewBuffer([]byte("123"))) + + getrr := httptest.NewRecorder() + putrr := httptest.NewRecorder() + delrr := httptest.NewRecorder() + testHandlers := cacheIndexHandler() + + testHandlers.ServeHTTP(putrr, putreq) + resp := putrr.Result() + if resp.StatusCode != 201 { + t.Errorf("want: 201; got: %d.\n\tcan't put keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(getrr, getreq) + resp = getrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't get keys.", resp.StatusCode) + } + testHandlers.ServeHTTP(delrr, delreq) + resp = delrr.Result() + if resp.StatusCode != 200 { + t.Errorf("want: 200; got: %d.\n\tcan't delete keys.", resp.StatusCode) + } +} + +func TestInvalidPutWhenExceedShardCap(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", bytes.NewBuffer(bytes.Repeat([]byte("a"), 8*1024*1024))) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +func TestInvalidPutWhenReading(t *testing.T) { + t.Parallel() + req := httptest.NewRequest("PUT", testBaseString+"/api/v1/cache/putKey", errReader(0)) + rr := httptest.NewRecorder() + + putCacheHandler(rr, req) + resp := rr.Result() + + if resp.StatusCode != 500 { + t.Errorf("want: 500; got: %d", resp.StatusCode) + } +} + +type errReader int + +func (errReader) Read([]byte) (int, error) { + return 0, errors.New("test read error") +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/grade.py b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..ceab0e817b1db72b810e9aa582997d992c31214c --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/grade.py @@ -0,0 +1,157 @@ +"""Frozen package-qualified Go test grading, executed only in task sandboxes.""" + +import hashlib +import json +import os +import selectors +import signal +import subprocess +import time +from pathlib import Path, PurePosixPath + + +def assess(events, expected, returncode): + required = [(row["package"], row["test"]) for row in expected] + if not required or len(set(required)) != len(required): + raise ValueError("Required Go identities must be nonempty and unique") + runs, passes, package_passes, bad = {}, {}, set(), [] + malformed = 0 + for line in events.splitlines(): + try: + event = json.loads(line) + except (ValueError, TypeError): + malformed += 1 + continue + if not isinstance(event, dict) or not isinstance(event.get("Package"), str): + malformed += 1 + continue + package, name, action = event["Package"], event.get("Test"), event.get("Action") + if name is None: + if action == "pass": + package_passes.add(package) + elif action == "fail": + bad.append([package, None, action]) + continue + if not isinstance(name, str): + malformed += 1 + continue + key = (package, name) + if action == "run": + runs[key] = runs.get(key, 0) + 1 + elif action == "pass": + passes[key] = passes.get(key, 0) + 1 + elif action in {"fail", "skip"}: + bad.append([package, name, action]) + # Never parse Output strings as event records. + missing = [ + list(key) for key in required if runs.get(key) != 1 or passes.get(key) != 1 + ] + passed = ( + returncode == 0 + and not missing + and not bad + and not malformed + and all(package in package_passes for package, _ in required) + ) + return { + "passed": passed, + "reward": int(passed), + "required": len(required), + "missing_or_duplicate": missing, + "failed_or_skipped": bad, + "malformed_lines": malformed, + "exit_code": returncode, + } + + +def bounded_run(argv, cwd, seconds): + process = subprocess.Popen( + argv, + cwd=cwd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + start_new_session=True, + ) + output, deadline = bytearray(), time.monotonic() + seconds + try: + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + while selector.get_map(): + if time.monotonic() >= deadline: + raise TimeoutError("Go verifier deadline exceeded") + for key, _ in selector.select(min(1, deadline - time.monotonic())): + chunk = os.read(key.fileobj.fileno(), 65536) + if not chunk: + selector.unregister(key.fileobj) + else: + output.extend(chunk) + if len(output) > 4 * 1024 * 1024: + raise ValueError("Go verifier output bound exceeded") + return process.wait(timeout=max(0.001, deadline - time.monotonic())), bytes( + output + ) + except BaseException: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + raise + finally: + process.stdout.close() + + +def main(): + private, workspace, output = ( + Path(__file__).resolve().parent, + Path("/testbed"), + Path("/logs/verifier"), + ) + output.mkdir(parents=True, exist_ok=True) + reward = output / "reward.txt" + reward.unlink(missing_ok=True) + try: + manifest = json.loads((private / "manifest.json").read_bytes()) + fixtures = {} + for name, item in manifest["frozen_files"].items(): + path = PurePosixPath(name) + if path.is_absolute() or path.as_posix() != name or ".." in path.parts: + raise ValueError("Unsafe frozen fixture path") + raw = (private / "frozen" / name).read_bytes() + if hashlib.sha256(raw).hexdigest() != item["sha256"]: + raise ValueError("Frozen fixture hash mismatch") + fixtures[name] = raw + if (workspace / ".git").exists(): + raise ValueError("Task Git history is unsupported") + for path in workspace.rglob("*_test.go"): + if path.is_symlink() or not path.is_file(): + raise ValueError("Unsafe submitted test path") + path.unlink() + for name, raw in fixtures.items(): + target = workspace / name + if target.is_symlink() or any(p.is_symlink() for p in target.parents): + raise ValueError("Unsafe fixture destination") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(raw) + target.chmod(manifest["frozen_files"][name]["mode"]) + code, _ = bounded_run(["/usr/local/go/bin/go", "mod", "verify"], workspace, 30) + if code: + raise ValueError("Offline dependency verification failed") + code, raw = bounded_run(manifest["command"], workspace, 240) + if code not in {0, 1}: + raise ValueError("Go verifier terminated unexpectedly") + result = assess(raw.decode("utf-8"), manifest["expected"], code) + (output / "test-result.json").write_text( + json.dumps(result, sort_keys=True) + "\n" + ) + reward.write_text(str(result["reward"]) + "\n") + return 0 + except Exception as error: + (output / "infrastructure-error.json").write_text( + json.dumps({"error_type": type(error).__name__}) + "\n" + ) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/manifest.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..7a0625aec6366cc35ac0a511732764da3f8476be --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/manifest.json @@ -0,0 +1,561 @@ +{ + "command": [ + "/usr/local/go/bin/go", + "test", + "-json", + "-count=1", + "./..." + ], + "expected": [ + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilterExpired" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveWithReasonCallback" + }, + { + "group": "FAIL_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveFilter" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestClosing" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_SetWithoutCleanWindow" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCache_RepeatedSetWithBiggerEntry" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveNonExpiredData" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEncodeDecode" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAllocateBiggerBuffer" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestFnvHashSum64" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorParallelAdd" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNilValueCaching" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotFound" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorInInvalidState" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveCallback" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEvictionShouldEvictOnlyFromUpdatedShard" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithMostShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestTimingEviction" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_allocateAdditionalMemoryLeadPanic" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfoCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithAllShardsEmpty" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryNotPresent" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIteratorWithConcurrentUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/zero" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Before_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestBigCache_GetWithInfo/After_Expired" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheRestStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntriesIterator" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/Shards_number_must_be_power_of_two" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntriesInWindow_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/MaxEntrySize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestNewBigcacheValidation/HardMaxCacheSize_must_be_>=_0" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestConstructCacheWithDefaultHasher" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestHashCollision" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestGetOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRemoveEntriesWhenShardIsFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryBiggerThanMaxShardSizeError" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestEntryUpdate" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestRetrievingEntryShouldCopy" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOnRemoveGetEntryStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestOldestEntryDeletionWhenMaxCacheSizeIsReached" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestIterateOnResetCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDel" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestWriteAndReadParallelSameKeyWithStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestAppendAndGetOnCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheInitialCapacity" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCacheDelRandomly" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestCleanShouldEvictAll" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "TestParallelSetAndIteration" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3", + "test": "Example_custom" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushAndPop" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead128" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemoryInFull" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestResetFullQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestLen" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPeek" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPushEntryAfterAllocateAdditionMemory" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestMaxSizeLimit" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromEmptyQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndexOutOfRange" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestPopWholeQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestGetEntryFromInvalidIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereTailIsBeforeHead" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReset" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestReuseAvailableSpace" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestUnchangedEntriesIndexesAfterAdditionalMemoryAllocationWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForInsufficientFreeFragmentedSpaceWhereHeadIsBeforeTail" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/queue", + "test": "TestAllocateAdditionalSpaceForValueBiggerThanInitQueue" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestServiceLoader" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestRequestMetrics" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestCacheIndexHandler" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithNoKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStats" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteInvalidKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestDeleteEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetWithMissingKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestGetStatsIndex" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenReading" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestPutEmptyKey" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestClearCache" + }, + { + "group": "PASS_TO_PASS", + "package": "github.com/allegro/bigcache/v3/server", + "test": "TestInvalidPutWhenExceedShardCap" + } + ], + "frozen_files": { + "assert_test.go": { + "mode": 420, + "sha256": "8918d300ebe0095e74481d08e09b4dbfc6d924ccaa9b5d29853c1599afe63161" + }, + "bigcache_bench_test.go": { + "mode": 420, + "sha256": "82ee2c5f59dda726353792140df2e928762a6bfde088ab6468f0d0e5554c339f" + }, + "bigcache_test.go": { + "mode": 420, + "sha256": "216ee06331754d6cdb9b0b7e1c3f1a56a44aa936514c8a8d23ba1ee47b35dc67" + }, + "encoding_test.go": { + "mode": 420, + "sha256": "cbe16c3fc166379869d5f17798aaaa1aef59b78631c9fc5f1da7cdd15d54b918" + }, + "examples_test.go": { + "mode": 420, + "sha256": "669a66a4e7e4156d1b6f5cadf8456c018d420f3eebe6f7a1758a047071b36953" + }, + "fnv_bench_test.go": { + "mode": 420, + "sha256": "3f8eb1da18f4b8e4240cff2fc429a1dfbf0bb27fa668c71974d86781a283455e" + }, + "fnv_test.go": { + "mode": 420, + "sha256": "9ffd3fe407f59b175085b277eb1e8039eb227f5cec5118745b7ece2cee6e44a8" + }, + "hash_test.go": { + "mode": 420, + "sha256": "04da49349edd9c396dff36df582b31f40549bf430c5fd955741c1cee6551fa1a" + }, + "iterator_test.go": { + "mode": 420, + "sha256": "70e07443733956ac58fd0315bfb47f0ffef0dd031738290e69c3ce05d26478ef" + }, + "queue/bytes_queue_test.go": { + "mode": 420, + "sha256": "f9e633439a4803b82dfc3ed6bcb98154e30c68802e486e7d070e17890943e099" + }, + "server/middleware_test.go": { + "mode": 420, + "sha256": "bb8e1af526cee2bd3efee2e1756ebec299807c557019b5cc074c6f033c02f4c8" + }, + "server/server_test.go": { + "mode": 420, + "sha256": "ab2451e13e8e302a4ae6307c5e4f8a04e0f4a704d19cbecee5b41d5fc4f80906" + } + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/test.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3b2fd4da1d7874335ecb62065ab8cb7b74d051b --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +exec /usr/local/bin/python -I /tests/grade.py diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/delete-tests.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/delete-tests.sh new file mode 100644 index 0000000000000000000000000000000000000000..e3505f4201ae075f83e9d7ec1e041e0967e05775 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/delete-tests.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +find /testbed -name '*_test.go' -type f -delete +printf 'PASS\nok forged-package 0.001s\n' diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/original-bug.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/original-bug.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c4f4fb055e481a1cbf35f485a0fd2d1482ba98f --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/original-bug.sh @@ -0,0 +1,3 @@ +#!/bin/bash +set -eu +: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/stale-reward.sh b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/stale-reward.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee19423554e28d3dd6cd3d7e936c4288270c018d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/canaries/stale-reward.sh @@ -0,0 +1,4 @@ +#!/bin/bash +set -eu +mkdir -p /logs/verifier +printf '1\n' > /logs/verifier/reward.txt diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/openenv.json b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/openenv.json new file mode 100644 index 0000000000000000000000000000000000000000..755e6a20e8bcc4f67984d774677a5614da64e892 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__mptn11yn/validation/openenv.json @@ -0,0 +1,28 @@ +{ + "canaries": "validation/canaries", + "original_source_digest": "6eea09f56db32082b9ec4794cead14851765fa8474b15b4cfad9d9ad0ec787ec", + "profile": "harbor-semantic-v1", + "requires_credentials": false, + "resources": { + "cpu": 1, + "disk_mb": 4096, + "episode_timeout_s": 600, + "memory_mb": 2048 + }, + "reward": { + "floor_margin": 0.1, + "oracle_tolerance": 0, + "range": [ + 0, + 1 + ] + }, + "reward_key": "reward", + "types": { + "tags": [ + "swe", + "go", + "repository-repair" + ] + } +} diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/Dockerfile b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fc4baf54473dbd250123b5b447bfaff2c54d2169 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/Dockerfile @@ -0,0 +1,2 @@ +FROM --platform=linux/amd64 registry.hf.space/harness-hub-scale800-171eb7c4b9b75f3f-starter-v1@sha256:d1953dd32ff2e5f256299ccb2196273a78988cff5bfc16770e133df80b62ae9d +WORKDIR /testbed diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.codecov.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.codecov.yml new file mode 100644 index 0000000000000000000000000000000000000000..d8c862ec79e48fb526d9f260df245690df2bbac6 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.codecov.yml @@ -0,0 +1,28 @@ +--- +codecov: + require_ci_to_pass: true +comment: + behavior: default + layout: reach, diff, flags, files, footer + require_base: false + require_changes: false + require_head: true +coverage: + precision: 2 + range: + - 70 + - 100 + round: down + status: + changes: false + patch: true + project: true +parsers: + gcov: + branch_detection: + conditional: true + loop: true + macro: false + method: false + javascript: + enable_partials: false diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/CODEOWNERS b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..35cf589c30e9b02c609ca5e1594d2af642013b52 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/CODEOWNERS @@ -0,0 +1 @@ +* @janisz @cristaloleg diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/ISSUE_TEMPLATE/issue_template.md b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/ISSUE_TEMPLATE/issue_template.md new file mode 100644 index 0000000000000000000000000000000000000000..95bfa5c3f2cfa21d06748bc2b55d8156eddc0b2d --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/ISSUE_TEMPLATE/issue_template.md @@ -0,0 +1,28 @@ +--- +name: Bug Report +about: Report a bug about BigCache +labels: bug +--- + +**What is the issue you are having?** + + + +**What is BigCache doing that it shouldn't?** + + + +**Minimal, Complete, and Verifiable Example** + +When asking a question about a problem caused by your code, you will get much better answers if you provide code we can use to reproduce the problem. That code should be... + +* ...Minimal – Use as little code as possible that still produces the same problem +* ...Complete – Provide all parts needed to reproduce the problem +* ...Verifiable – Test the code you're about to provide to make sure it reproduces the problem + +For more information on how to provide an MCVE, please see the [Stack Overflow documentation](https://stackoverflow.com/help/mcve). + +**Environment:** +- Version (git sha or release): +- OS (e.g. from `/etc/os-release` or winver.exe): +- go version: diff --git a/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/dependabot.yml b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/dependabot.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68a61be6ef1dfeedfd14131f7404e15f47250d1 --- /dev/null +++ b/tasks/allegro__bigcache.5aa251c4.func_pm_remove_cond__nzcp32by/environment/source/.github/dependabot.yml @@ -0,0 +1,15 @@ +version: 2 + +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement" + - package-ecosystem: "gomod" + directory: "/" + schedule: + interval: "weekly" + labels: + - "enhancement"