diff --git a/strata_cli/launch/params.py b/strata_cli/launch/params.py index 7297d90c..f6af060b 100644 --- a/strata_cli/launch/params.py +++ b/strata_cli/launch/params.py @@ -12,6 +12,8 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Any +from strata_control.user_args import MULTI_VALUE_FLAGS + _ENTRY = re.compile(r"^ (--[A-Za-z0-9][A-Za-z0-9-]*)( +)?(.*)$") _EXPERIMENTAL = re.compile(r"experimental|diagnostic|A/B arm|fault injection|oracle", re.I) _DEFAULT = re.compile(r"\(\s*default[: ]\s*([^)]*)\)", re.I) @@ -132,8 +134,11 @@ def argv_to_dict(argv: list[Any]) -> dict[str, str]: tok = items[i] if tok.startswith("--"): if i + 1 < len(items) and not items[i + 1].startswith("--"): - out[tok] = items[i + 1] - i += 2 + n = 1 + while n < MULTI_VALUE_FLAGS.get(tok, 1) and i + 1 + n < len(items) and not items[i + 1 + n].startswith("--"): + n += 1 + out[tok] = " ".join(items[i + 1:i + 1 + n]) + i += 1 + n continue out[tok] = "" i += 1 diff --git a/strata_cli/launch/settings.py b/strata_cli/launch/settings.py index 3b568465..1b0ba729 100644 --- a/strata_cli/launch/settings.py +++ b/strata_cli/launch/settings.py @@ -252,6 +252,8 @@ def as_argv_changes(extra: dict[str, str], bool_flags: frozenset[str]) -> tuple[ for key, value in extra.items(): if key.startswith("--"): low = value.lower() + if low == "" and key not in bool_flags: + continue # an empty value for an option that takes one is no change, never a bare flag (#3504) if key in bool_flags or low in ("on", "true", "yes", ""): args[key] = None if low in ("off", "false", "no", "none") else True elif low in ("off", "false", "no", "none"): diff --git a/strata_control/tune_knobs.py b/strata_control/tune_knobs.py index 259d7296..54f27f72 100644 --- a/strata_control/tune_knobs.py +++ b/strata_control/tune_knobs.py @@ -19,6 +19,8 @@ from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Callable, Sequence +from strata_control import user_args + ANSWER_ORDER = ("exact", "placement", "nonrepeatable", "quality") #: What the Tune screen says about a preset's answer class (3.4), in plain words. @@ -450,15 +452,27 @@ def _norm(value: Any) -> str | None: def _current(argv: Sequence[str], flag: str) -> str | None: - """The value a flag has in an argv list: '' for a bare flag, None when absent.""" + """The value a flag has in an argv list: '' for a bare flag, None when absent (several values joined by a space).""" for i, a in enumerate(argv): if a == flag: if flag in BOOL_FLAGS or i + 1 >= len(argv) or str(argv[i + 1]).startswith("--"): return "" - return str(argv[i + 1]) + return " ".join(str(x) for x in argv[i + 1:i + 1 + _value_count(argv, i)]) return None +def _value_count(argv: Sequence[str], i: int) -> int: + """How many entries after the flag at ``argv[i]`` are its values: none for a bool flag, as many as the option takes + (``--control-vector-layer-range 4 44`` is two) up to the next ``--option``.""" + flag = argv[i] + if flag in BOOL_FLAGS: + return 0 + n = 0 + while n < user_args.MULTI_VALUE_FLAGS.get(flag, 1) and i + 1 + n < len(argv) and not str(argv[i + 1 + n]).startswith("--"): + n += 1 + return n + + def signature(args: dict[str, Any], env: dict[str, str | None] | None = None) -> str: parts = [f"{k}={_norm(v)}" for k, v in sorted(args.items())] + [f"{k}={v}" for k, v in sorted((env or {}).items())] return "|".join(parts) @@ -471,8 +485,7 @@ def apply_to_argv(argv: Sequence[str], args: dict[str, Any]) -> list[str]: i = 0 while i < len(out): if out[i] == flag: - n = 1 if (flag in BOOL_FLAGS or i + 1 >= len(out) or str(out[i + 1]).startswith("--")) else 2 - del out[i:i + n] + del out[i:i + 1 + _value_count(out, i)] else: i += 1 if value is None or value is False: @@ -480,7 +493,7 @@ def apply_to_argv(argv: Sequence[str], args: dict[str, Any]) -> list[str]: if value is True or flag in BOOL_FLAGS: out.append(flag) else: - out.extend([flag, str(value)]) + out.extend([flag, *user_args.value_tokens(flag, value)]) return out diff --git a/strata_control/user_args.py b/strata_control/user_args.py index ce698aa1..f2f6c108 100644 --- a/strata_control/user_args.py +++ b/strata_control/user_args.py @@ -18,6 +18,7 @@ captured, so their own changes are never mistaken for the person's. from __future__ import annotations +import re from typing import Any USER_KEY = "user_args" @@ -29,6 +30,21 @@ USER_KEPT_FLAGS = frozenset({"--control-vector", "--control-vector-scaled", "--c "--cvec-dir"}) +#: options that take more than one value, and how many (``--control-vector-layer-range 4 44``): written as separate argv +#: entries, never as one ``4,44``, and removed with all of their values (#3504) +MULTI_VALUE_FLAGS = {"--control-vector-layer-range": 2} + + +def value_tokens(flag: str, value: Any) -> list[str]: + """The argv entries that follow ``flag`` for ``value``: one, or the several a multi-value option takes (``4 44``, ``4,44``, + ``4-44`` or a list).""" + n = MULTI_VALUE_FLAGS.get(flag, 1) + if n == 1: + return [str(value)] + parts = [str(v) for v in value] if isinstance(value, (list, tuple)) else re.split(r"[,;\s]+|(?<=\d)-(?=\d)", str(value).strip()) + return [t for t in parts if t] + + def groups(args: Any) -> list[list[str]]: """Split an argument list into groups: an option and the values after it (up to the next ``--option``).""" out: list[list[str]] = [] @@ -114,5 +130,5 @@ def set_flag(user: list[str], flag: str, value: Any) -> list[str]: """``user`` with ``flag`` set to ``value`` (None: the person's option removed).""" rest = [g for g in groups(user) if flag_of(g) != flag] if value is not None: - rest.append([flag, str(value)]) + rest.append([flag, *value_tokens(flag, value)]) return flat(rest) diff --git a/tests/terminal/test_issues_022.py b/tests/terminal/test_issues_022.py index 79c4b9b1..92cf35b3 100644 --- a/tests/terminal/test_issues_022.py +++ b/tests/terminal/test_issues_022.py @@ -419,5 +419,43 @@ class Issue3501TrashOnPosix(unittest.TestCase): self.assertFalse(discovery.in_trash(r"C:\Users\a\Strata")) + +class Issue3504MultiValueArgs(unittest.TestCase): + """Advanced settings: a two-value option is two argv entries, `off` removes all of its values, an empty value is no bare flag.""" + + ARGS = ["--max-context", "131072", "--control-vector-layer-range", "4", "44", "--cvec-dir", "per-layer", + "--conversation-cache-mib", "8192"] + + def test_two_values_are_two_entries(self): + from strata_control import tune_knobs + for typed in ("4,44", "4 44", "4-44"): + out = tune_knobs.apply_to_argv(self.ARGS, {"--control-vector-layer-range": typed}) + i = out.index("--control-vector-layer-range") + self.assertEqual(out[i + 1:i + 3], ["4", "44"], typed) + self.assertEqual(out.count("--control-vector-layer-range"), 1) + + def test_off_removes_the_option_and_every_value(self): + from strata_cli.launch import settings as S + from strata_control import tune_knobs + extra = {"--control-vector-layer-range": "off", "--cvec-dir": "off"} + a, _ = S.as_argv_changes(extra, tune_knobs.BOOL_FLAGS) + out = tune_knobs.apply_to_argv(self.ARGS, a) + self.assertEqual(out, ["--max-context", "131072", "--conversation-cache-mib", "8192"]) + + def test_an_empty_value_is_no_bare_flag(self): + from strata_cli.launch import settings as S + from strata_control import tune_knobs + a, _ = S.as_argv_changes({"--cvec-dir": "", "--kv-grow": ""}, tune_knobs.BOOL_FLAGS) + self.assertEqual(a, {"--kv-grow": True}) + self.assertEqual(tune_knobs.apply_to_argv(self.ARGS, a)[:-1].count("--cvec-dir"), 1) + + def test_set_flag_and_the_table_keep_both_values(self): + from strata_cli.launch import params + from strata_control import user_args + self.assertEqual(user_args.set_flag([], "--control-vector-layer-range", "4,44"), + ["--control-vector-layer-range", "4", "44"]) + self.assertEqual(params.argv_to_dict(self.ARGS)["--control-vector-layer-range"], "4 44") + + if __name__ == "__main__": unittest.main()