diff --git a/score/kvs/rust_kvs/tests/test_scenarios/cit/persistency.rs b/score/kvs/rust_kvs/tests/test_scenarios/cit/persistency.rs index 469037c7e8..c1797753dd 100644 --- a/score/kvs/rust_kvs/tests/test_scenarios/cit/persistency.rs +++ b/score/kvs/rust_kvs/tests/test_scenarios/cit/persistency.rs @@ -399,6 +399,39 @@ impl Scenario for SetAndFlush { } } +/// Flush a one-character string, then a string of "large_value_bytes" characters. +/// +/// Log "small_flush_ok", true if the first flush succeeded. +/// Log "large_flush", "ok" if the second flush succeeded, else the name of its error code. +struct FlushStorageLimit; + +impl Scenario for FlushStorageLimit { + fn name(&self) -> &str { + "flush_storage_limit" + } + + fn run(&self, input: &str) -> Result<(), String> { + let v: Value = serde_json::from_str(input).expect("Failed to parse input string"); + let large_value_bytes: usize = serde_json::from_value(v["large_value_bytes"].clone()) + .expect("Failed to parse \"large_value_bytes\" field"); + let params = KvsParameters::from_value(&v).expect("Failed to parse parameters"); + let kvs = kvs_instance(params).expect("Failed to create KVS instance"); + + kvs.set_value("small", "s").expect("Failed to set small"); + info!(small_flush_ok = kvs.flush().is_ok()); + + kvs.set_value("large", "l".repeat(large_value_bytes)) + .expect("Failed to set large"); + let large_flush = match kvs.flush() { + Ok(()) => "ok".to_string(), + Err(e) => format!("{e:?}"), + }; + info!(large_flush); + + Ok(()) + } +} + pub fn persistency_group() -> Box { Box::new(ScenarioGroupImpl::new( "persistency", @@ -413,6 +446,7 @@ pub fn persistency_group() -> Box { Box::new(RecoverFromSnapshot), Box::new(FailedFlush), Box::new(SetAndFlush), + Box::new(FlushStorageLimit), ], vec![], )) diff --git a/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_instance.rs b/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_instance.rs index d4be696bc6..3379777da8 100644 --- a/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_instance.rs +++ b/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_instance.rs @@ -45,6 +45,9 @@ pub fn kvs_instance(kvs_parameters: KvsParameters) -> Result { set_backend = true; } + // Rust has no storage size limit (#810), so "max_storage_bytes" is not applied. + let _ = kvs_parameters.max_storage_bytes; + // Set backend, if backend parameters were provided. if set_backend { builder = builder.backend(Box::new(backend_builder.build())); diff --git a/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_parameters.rs b/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_parameters.rs index 62bf54d039..feefa6c959 100644 --- a/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_parameters.rs +++ b/score/kvs/rust_kvs/tests/test_scenarios/helpers/kvs_parameters.rs @@ -29,6 +29,7 @@ pub struct KvsParameters { pub kvs_load: Option, pub dir: Option, pub snapshot_max_count: Option, + pub max_storage_bytes: Option, } impl KvsParameters { diff --git a/score/kvs/tests/test_cases/tests/test_cit_constraints.py b/score/kvs/tests/test_cases/tests/test_cit_constraints.py new file mode 100644 index 0000000000..57c29e078b --- /dev/null +++ b/score/kvs/tests/test_cases/tests/test_cit_constraints.py @@ -0,0 +1,334 @@ +# ******************************************************************************* +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 +# +# SPDX-License-Identifier: Apache-2.0 +# ******************************************************************************* +import json +import shlex +from collections.abc import Generator +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import pytest +from common import CommonScenario, ResultCode, execute_checked, scenario_command, temp_dir_common, write_file_on_target +from score.itf.plugins.core import Target +from test_properties import add_test_properties +from testing_utils import LogContainer, ScenarioResult + +pytestmark = pytest.mark.parametrize("version", ["cpp", "rust"], scope="class") + +INSTANCE_ID = 1 +BUILDER_MAX_COUNT = 2 +FILE_MAX_COUNT = 1 + +# A flush of one character stays far below LOW_STORAGE_LIMIT. +# A flush of 2048 characters needs about 2350 bytes, between the two limits. +LOW_STORAGE_LIMIT = 1024 +HIGH_STORAGE_LIMIT = 8192 + +CONFIG_FILE = "kvs_config.json" +FILE_ENTRY = {"instance_id": INSTANCE_ID, "snapshot_count_limit": FILE_MAX_COUNT} + +RUST_NO_CONFIG_FILE = "Rust KVS has no configuration-file support (#809)" +RUST_NO_STORAGE_LIMIT = ( + "Rust KVS has no storage size limit (#810), and no configuration-file support for the file cases (#809)" +) + + +@dataclass(frozen=True) +class MaxCountCase: + """Builder parameters, configuration file and expected maximum; paths are relative to the working folder.""" + + builder: dict[str, int] + expected_max_count: int + file_path: str | None = None + env_path: str | None = None + file_entry: dict[str, int] | None = None + rust_defect: str | None = None + rust_unverified: str | None = None + + +MAX_COUNT_CASES = { + "default": MaxCountCase(builder={}, expected_max_count=3), + "builder": MaxCountCase( + builder={"snapshot_max_count": BUILDER_MAX_COUNT}, + expected_max_count=BUILDER_MAX_COUNT, + ), + "env_file": MaxCountCase( + builder={}, + expected_max_count=FILE_MAX_COUNT, + file_path="constraints.json", + env_path="constraints.json", + file_entry=FILE_ENTRY, + rust_defect=RUST_NO_CONFIG_FILE, + ), + "env_dir": MaxCountCase( + builder={}, + expected_max_count=FILE_MAX_COUNT, + file_path="config/kvs_config.json", + env_path="config", + file_entry=FILE_ENTRY, + rust_defect=RUST_NO_CONFIG_FILE, + ), + "cwd_fallback": MaxCountCase( + builder={}, + expected_max_count=FILE_MAX_COUNT, + file_path="etc/kvs_config.json", + file_entry=FILE_ENTRY, + rust_defect=RUST_NO_CONFIG_FILE, + ), + "below_builder": MaxCountCase( + builder={"snapshot_max_count": BUILDER_MAX_COUNT}, + expected_max_count=FILE_MAX_COUNT, + file_path="constraints.json", + env_path="constraints.json", + file_entry=FILE_ENTRY, + rust_defect=RUST_NO_CONFIG_FILE, + ), + "above_builder": MaxCountCase( + builder={"snapshot_max_count": 1}, + expected_max_count=2, + file_path="constraints.json", + env_path="constraints.json", + file_entry={"instance_id": INSTANCE_ID, "snapshot_count_limit": 2}, + rust_defect=RUST_NO_CONFIG_FILE, + ), + "other_instance": MaxCountCase( + builder={"snapshot_max_count": BUILDER_MAX_COUNT}, + expected_max_count=BUILDER_MAX_COUNT, + file_path=CONFIG_FILE, + env_path=CONFIG_FILE, + file_entry={"instance_id": 2, "snapshot_count_limit": FILE_MAX_COUNT}, + rust_unverified=RUST_NO_CONFIG_FILE, + ), + "limit_unset": MaxCountCase( + builder={"snapshot_max_count": BUILDER_MAX_COUNT}, + expected_max_count=BUILDER_MAX_COUNT, + file_path=CONFIG_FILE, + env_path=CONFIG_FILE, + file_entry={"instance_id": INSTANCE_ID}, + rust_unverified=RUST_NO_CONFIG_FILE, + ), +} + + +# Logged error of a flush over the limit: C++ logs the message of kOutOfStorageSpace, Rust the ErrorCode name. +OUT_OF_STORAGE_SPACE = {"cpp": "Out of storage space", "rust": "OutOfStorageSpace"} +FLUSH_OK = {"cpp": "ok", "rust": "ok"} + + +@dataclass(frozen=True) +class StorageLimitCase: + builder: dict[str, int] + large_flush: dict[str, str] + file_limit: int | None = None + rust_defect: str | None = None + rust_unverified: str | None = None + + +STORAGE_LIMIT_CASES = { + "builder": StorageLimitCase( + builder={"max_storage_bytes": LOW_STORAGE_LIMIT}, + large_flush=OUT_OF_STORAGE_SPACE, + rust_defect="Rust KVS has no storage size limit (#810)", + ), + "file": StorageLimitCase( + builder={}, + large_flush=OUT_OF_STORAGE_SPACE, + file_limit=LOW_STORAGE_LIMIT, + rust_defect=RUST_NO_STORAGE_LIMIT, + ), + "file_below_builder": StorageLimitCase( + builder={"max_storage_bytes": HIGH_STORAGE_LIMIT}, + large_flush=OUT_OF_STORAGE_SPACE, + file_limit=LOW_STORAGE_LIMIT, + rust_defect=RUST_NO_STORAGE_LIMIT, + ), + "no_limit": StorageLimitCase(builder={}, large_flush=FLUSH_OK), + "file_above_builder": StorageLimitCase( + builder={"max_storage_bytes": LOW_STORAGE_LIMIT}, + large_flush=FLUSH_OK, + file_limit=HIGH_STORAGE_LIMIT, + rust_unverified=RUST_NO_STORAGE_LIMIT, + ), +} + + +def write_config_on_target(target: Target, path: Path, entry: dict[str, int]) -> None: + """ + Write a configuration file with one instance entry on the target, with its parent folders. + """ + content = json.dumps({"format_version": 1, "key_value_storage_list": [entry]}).encode() + execute_checked(target, f"mkdir -p {shlex.quote(str(path.parent))}") + write_file_on_target(target, path, content) + + +class ConfigScenario(CommonScenario): + """ + Runs a scenario in an own working folder per case, with KVS_CONFIG_PATH from 'config_path'. + """ + + @pytest.fixture(scope="class") + def temp_dir(self, target: Target, version: str, case: str) -> Generator[Path, None, None]: + # Own working folder per case, because each case writes its own configuration file. + yield from temp_dir_common(target, self.__class__.__name__, version, case) + + @pytest.fixture(scope="class") + def command( + self, + target_path: Path, + scenario_name: str, + test_config: dict[str, Any], + temp_dir: Path, + config_path: str | None, + ) -> list[str]: + scenario = shlex.join(scenario_command(target_path, scenario_name, test_config)) + folder = shlex.quote(str(temp_dir)) + environment = ( + "env -u KVS_CONFIG_PATH" if config_path is None else f"env KVS_CONFIG_PATH={shlex.quote(config_path)}" + ) + # The QNX image has "sh" only as "/bin/sh", not in the PATH. + return ["/bin/sh", "-c", f"cd {folder} && exec {environment} {scenario}"] + + +@add_test_properties( + partially_verifies=[ + "comp_req__kvs__constraints", + "comp_req__kvs__constraints_priority", + "comp_req__kvs__snapshot_max_num_cfg", + ], + test_type="requirements-based", + derivation_technique="equivalence-classes", +) +@pytest.mark.parametrize("case", list(MAX_COUNT_CASES), scope="class") +class TestSnapshotMaxCountConstraint(ConfigScenario): + """ + Verifies which maximum number of snapshots applies: the default, the builder value or the file value. + The file is named by KVS_CONFIG_PATH, is in the folder named by it, or is "etc/kvs_config.json". + A file value applies over the builder value, below or above it. + A file without a value for the instance keeps the builder value. + """ + + @pytest.fixture(scope="class") + def scenario_name(self) -> str: + return "cit.snapshots.max_count" + + @pytest.fixture(scope="class") + def config_path(self, target: Target, temp_dir: Path, case: str) -> str | None: + data = MAX_COUNT_CASES[case] + if data.file_path is not None: + write_config_on_target(target, temp_dir / data.file_path, data.file_entry) + return data.env_path + + @pytest.fixture(scope="class") + def test_config(self, temp_dir: Path, case: str) -> dict[str, Any]: + builder = MAX_COUNT_CASES[case].builder + return {"kvs_parameters": {"instance_id": INSTANCE_ID, "dir": str(temp_dir), **builder}} + + def test_max_count( + self, + request: pytest.FixtureRequest, + version: str, + case: str, + results: ScenarioResult, + logs_info_level: LogContainer, + ): + """ + Checks that the KVS uses the expected maximum number of snapshots of the case. + + Steps: + 1. Write the configuration file of the case, if any, at its location. + 2. Start the scenario in the folder, with KVS_CONFIG_PATH of the case or unset. + 3. Open the KVS with the builder parameters of the case. + 4. Log the maximum number of snapshots of the KVS. + + Expected result: + - The scenario ends without an error. + - The maximum is the file value if the file sets one for the instance. + - Otherwise it is the builder value, or the default of 3. + + Known defect: Rust has no configuration-file support (#809), so the file cases are strict xfails. + The cases that expect the builder value pass in Rust only by ignoring the file, so they xfail too. + """ + assert results.return_code == ResultCode.SUCCESS, results.stderr + data = MAX_COUNT_CASES[case] + if version == "rust" and data.rust_defect: + request.applymarker(pytest.mark.xfail(strict=True, raises=AssertionError, reason=data.rust_defect)) + if version == "rust" and data.rust_unverified: + pytest.xfail(data.rust_unverified) + assert [log.max_count for log in logs_info_level.get_logs("max_count")] == [data.expected_max_count] + + +@add_test_properties( + partially_verifies=["comp_req__kvs__constraints", "comp_req__kvs__constraints_priority"], + test_type="requirements-based", + derivation_technique="equivalence-classes", +) +@pytest.mark.parametrize("case", list(STORAGE_LIMIT_CASES), scope="class") +class TestStorageLimitConstraint(ConfigScenario): + """ + Verifies that a flush fails when it would exceed the effective storage size limit, and succeeds otherwise. + The limit of 1024 bytes comes from the builder, from the file, or from the file over a builder limit of 8192. + The flush succeeds without a limit, or when a file limit of 8192 overrides a builder limit of 1024. + """ + + @pytest.fixture(scope="class") + def scenario_name(self) -> str: + return "cit.persistency.flush_storage_limit" + + @pytest.fixture(scope="class") + def config_path(self, target: Target, temp_dir: Path, case: str) -> str | None: + file_limit = STORAGE_LIMIT_CASES[case].file_limit + if file_limit is None: + return None + write_config_on_target( + target, temp_dir / CONFIG_FILE, {"instance_id": INSTANCE_ID, "storage_quota": file_limit} + ) + return CONFIG_FILE + + @pytest.fixture(scope="class") + def test_config(self, temp_dir: Path, case: str) -> dict[str, Any]: + builder = STORAGE_LIMIT_CASES[case].builder + parameters = {"instance_id": INSTANCE_ID, "dir": str(temp_dir), **builder} + return {"kvs_parameters": parameters, "large_value_bytes": 2048} + + def test_large_flush( + self, + request: pytest.FixtureRequest, + version: str, + case: str, + results: ScenarioResult, + logs_info_level: LogContainer, + ): + """ + Checks that a flush within the limit succeeds and a larger flush succeeds or fails as the case expects. + + Steps: + 1. Set the builder limit and write the file limit of the case, if any. + 2. Open the KVS in an empty folder, set a one-character string and flush. + 3. Set a string of 2048 characters, flush, and log "ok" or the error of the flush. + + Expected result: + - The scenario ends without an error, and the first flush succeeds. + - The second flush fails with kOutOfStorageSpace if the effective limit is 1024 bytes, and succeeds otherwise. + + Known defect: Rust has no storage size limit (#810) and no configuration-file support (#809). + Cases with a limit of 1024 are strict xfails; "file_above_builder" passes only by ignoring both, so it xfails. + """ + assert results.return_code == ResultCode.SUCCESS, results.stderr + small_flushes = [log.small_flush_ok for log in logs_info_level.get_logs("small_flush_ok")] + assert small_flushes == [True], "precondition: the flush within the limit failed" + data = STORAGE_LIMIT_CASES[case] + if version == "rust" and data.rust_defect: + request.applymarker(pytest.mark.xfail(strict=True, raises=AssertionError, reason=data.rust_defect)) + if version == "rust" and data.rust_unverified: + pytest.xfail(data.rust_unverified) + assert [log.large_flush for log in logs_info_level.get_logs("large_flush")] == [data.large_flush[version]] diff --git a/score/kvs/tests/test_scenarios/cit/persistency.cpp b/score/kvs/tests/test_scenarios/cit/persistency.cpp index 2782532d02..7711fbe731 100644 --- a/score/kvs/tests/test_scenarios/cit/persistency.cpp +++ b/score/kvs/tests/test_scenarios/cit/persistency.cpp @@ -523,6 +523,38 @@ class SetAndFlush final : public Scenario } }; +/// @brief Flushes a one-character string, then a string of "large_value_bytes" characters. +/// +/// Logs "small_flush_ok", true if the first flush succeeded. +/// Logs "large_flush", "ok" if the second flush succeeded, else the message of its error code. +class FlushStorageLimit final : public Scenario +{ + public: + ~FlushStorageLimit() final = default; + + std::string name() const final + { + return "flush_storage_limit"; + } + + void run(const std::string& input) const final + { + const auto object{ParseInput(input)}; + const auto large_value_bytes{object.at("large_value_bytes").As().value()}; + auto kvs{KvsInstance(KvsParameters::FromValue(object))}; + + Check("set small", kvs->SetValue("small", KvsValue{"s"})); + TRACING_INFO(kTargetName, std::pair{std::string{"small_flush_ok"}, kvs->Flush().has_value()}); + + Check("set large", kvs->SetValue("large", KvsValue{std::string(large_value_bytes, 'l')})); + const auto large_flush{kvs->Flush()}; + TRACING_INFO( + kTargetName, + std::pair{std::string{"large_flush"}, + large_flush.has_value() ? std::string{"ok"} : std::string{large_flush.error().Message()}}); + } +}; + ScenarioGroup::Ptr PersistencyGroup() { return ScenarioGroup::Ptr{new ScenarioGroupImpl{"persistency", @@ -534,6 +566,7 @@ ScenarioGroup::Ptr PersistencyGroup() std::make_shared(), std::make_shared(), std::make_shared(), - std::make_shared()}, + std::make_shared(), + std::make_shared()}, {}}}; } diff --git a/score/kvs/tests/test_scenarios/helpers/kvs_instance.cpp b/score/kvs/tests/test_scenarios/helpers/kvs_instance.cpp index d1d8fe56d4..3f12fa5981 100644 --- a/score/kvs/tests/test_scenarios/helpers/kvs_instance.cpp +++ b/score/kvs/tests/test_scenarios/helpers/kvs_instance.cpp @@ -42,6 +42,10 @@ std::shared_ptr KvsInstance(const KvsParameters& params) { builder.SnapshotMaxCount(*params.snapshot_max_count); } + if (params.max_storage_bytes.has_value()) + { + builder.MaxStorageBytes(params.max_storage_bytes); + } // Build KVS instance. auto build_result{builder.Build()}; diff --git a/score/kvs/tests/test_scenarios/helpers/kvs_parameters.cpp b/score/kvs/tests/test_scenarios/helpers/kvs_parameters.cpp index 587b94f783..5ec66e7c45 100644 --- a/score/kvs/tests/test_scenarios/helpers/kvs_parameters.cpp +++ b/score/kvs/tests/test_scenarios/helpers/kvs_parameters.cpp @@ -90,5 +90,10 @@ KvsParameters KvsParameters::FromValue(const Object& object) params.snapshot_max_count = obj_root.at("snapshot_max_count").As().value(); } + if (obj_root.find("max_storage_bytes") != obj_root.end()) + { + params.max_storage_bytes = obj_root.at("max_storage_bytes").As().value(); + } + return params; } diff --git a/score/kvs/tests/test_scenarios/helpers/kvs_parameters.h b/score/kvs/tests/test_scenarios/helpers/kvs_parameters.h index c3b6787f89..b3b587f11a 100644 --- a/score/kvs/tests/test_scenarios/helpers/kvs_parameters.h +++ b/score/kvs/tests/test_scenarios/helpers/kvs_parameters.h @@ -36,6 +36,7 @@ struct KvsParameters std::optional kvs_load{}; std::optional dir{}; std::optional snapshot_max_count{}; + std::optional max_storage_bytes{}; }; #endif // SCORE_KVS_TESTS_TEST_SCENARIOS_HELPERS_KVS_PARAMETERS_H