From 26d3e607f5589fa10ad765ce8b363f2e0d864f3f Mon Sep 17 00:00:00 2001 From: benmandrew Date: Tue, 24 Nov 2026 17:11:37 +0000 Subject: [PATCH 1/2] feat(scope): keep a FRET mode formula in the scope itself FRET scopes over a mode formula, such as `in (PCVMode | PSVMode)`, were imported as a fresh output atom plus a non-weakenable guarantee `G(m <-> f)`. That definition inflated the spec, and the repair search had to carry it as an extra output and an extra guarantee. `Scope::m_mode` may now hold the formula itself. A bare mode lowers, hashes and serialises byte-for-byte as before, so no determinism golden moved. Mutation never edits a mode and similarity compares it as text, and both are unchanged. A formula mode stays out of `modes`, and counting adds the formula's atoms. The importer writes the canonical formula and drops the fresh atom. examples/ventilator-controller is re-imported: guarantees go from 68 to 58, outputs from 63 to 53 and modes from 20 to 10. Checks: - ctest passes 70/70, and lint and format are clean. - All 11 formula-mode requirements are equivalent under ltlfilt to FRET's ftExpanded at ordinal ticks. - Of the 58 new guarantees, 47 have identical LTL. The other 11 are ltlfilt-equivalent to the old ones with the mode atom replaced by its definition. The assumption is unchanged. - Two small `in (a | b)` specs give the same realize verdict both ways: one is realizable and one is not. - The full ventilator was not put through realize, which is too slow. --- docs/dev/config-and-provenance.md | 1 + docs/dev/fretish-scopes.md | 6 +- examples/README.md | 2 +- examples/ventilator-controller/spec.json | 132 ++--------------------- include/requirement.hpp | 25 ++++- include/serialisation.hpp | 42 +++++++- schemas/specification.schema.json | 2 +- scripts/import_fret.py | 125 ++++++++++++++------- scripts/test_import_fret.py | 37 +++---- src/fitness/transfer_matrix.cpp | 6 +- src/requirement.cpp | 76 +++++++++++-- test/fitness/transfer_matrix_tests.cpp | 19 ++++ test/scope_tests.cpp | 73 +++++++++++++ test/serialisation_tests.cpp | 49 +++++++++ 14 files changed, 393 insertions(+), 202 deletions(-) diff --git a/docs/dev/config-and-provenance.md b/docs/dev/config-and-provenance.md index 4c581f85..d2ef2c28 100644 --- a/docs/dev/config-and-provenance.md +++ b/docs/dev/config-and-provenance.md @@ -93,3 +93,4 @@ Rows dated before 2026-10-29, with the notes on the selection renames and the va | 2026-11-18 | `mutation.gate_realizable` | added at `"exchange"` (was `"towards"` before the key existed) | Moves only runs with `direction_gated` on: a realisable parent now takes one step towards the original and weakens one slot still equal to it, instead of only stepping back. A config that sets `direction_gated = true` without the key, such as those of `2026-11-05-fretish-order`, now runs exchange; write `gate_realizable = "towards"` to reproduce it. With the gate off, the default since the key was added, the key is never read and every archive reproduces seed for seed. `mutation.blame_realizable` was added at `true`, which behaves as before. | | 2026-11-19 | `filters.climb_orders` | re-added at `1` | Restores the hash-priority restarts of the output climb that the 2026-11-18 row removed; `filters.climb_order` stays retired. At 1 the climb runs once per repair in slot order, as it did while the key was retired, so every archive reproduces as before and the determinism goldens did not move. The order of each extra climb draws no random number. | | 2026-11-19 | `genetic.maximality_removal` | added at `false` | Ported from `feat/demotion-removal` (5e94f6b5), which the 2026-11-17 and 2026-11-18 removal campaigns ran from their own branches. Acts only with `maximality_demotion` on, and is rejected without it. At `false` selection is unchanged, so every archive reproduces seed for seed with the key omitted. | +| 2026-11-24 | — (example) | `examples/ventilator-controller` re-imported with formula modes | The 10 fresh `mode_*` output atoms and their 10 non-weakenable definitions are gone: each of the 11 formula-mode scopes now names its formula, and the spec has 58 guarantees, 53 outputs and 10 modes where it had 68, 63 and 20. Every other guarantee, the assumption and the inputs are unchanged, and each of the 58 remaining guarantees is equivalent under `ltlfilt` to its old form with the `mode_*` atom replaced by its definition. A campaign on `ventilator-controller` before this date ran the old spec, which its recorded commit and provenance tag still check out; a new run on it is not comparable with those. No other example has a formula mode, and the determinism goldens did not move. See "FRETISH scopes" in `docs/dev/fretish-scopes.md`. | diff --git a/docs/dev/fretish-scopes.md b/docs/dev/fretish-scopes.md index 204e6a28..b5831391 100644 --- a/docs/dev/fretish-scopes.md +++ b/docs/dev/fretish-scopes.md @@ -4,7 +4,7 @@ The scope field of a FRETISH requirement: its lowering, its validation against t ## FRETISH scopes -`Requirement::m_scope` (`include/requirement.hpp`) is FRET's fifth field, the interval over which a requirement is enforced relative to when a *mode* holds. `ScopeKind` has eight values, every scope FRETISH text can reach: Global (the default), In, NotIn, Before, After, OnlyIn, OnlyBefore and OnlyAfter. The spellings are `in m` (also `during`, `while`), `except in m` (also `unless in`, `when not in`), `before m`, `after m`, `only in m`, `only before m` and `only after m`. A bare `not in` is a parse error, as is a formula mode such as `in (a & b)`. +`Requirement::m_scope` (`include/requirement.hpp`) is FRET's fifth field, the interval over which a requirement is enforced relative to when a *mode* holds. `ScopeKind` has eight values, every scope FRETISH text can reach: Global (the default), In, NotIn, Before, After, OnlyIn, OnlyBefore and OnlyAfter. The spellings are `in m` (also `during`, `while`), `except in m` (also `unless in`, `when not in`), `before m`, `after m`, `only in m`, `only before m` and `only after m`. A bare `not in` is a parse error. The lowering is in `src/requirement.cpp`. Each scope adds an outer wrapper and a boundary marker `B` that discharges a bounded obligation early: `EoM = (m & X!m)` for In and OnlyAfter, `SoM = (!m & X(m))` for NotIn, Before and OnlyIn, and none for Global, After and OnlyBefore. The operand of `X` is always parenthesised in the rendered text: SPOT reads `Xm` as `X(m)`, but PEREDUR's own parser and black read it as one atom `Xm`, which until this was fixed made the fingerprint prefilter refute true implications on every mode-scoped spec; `test_scope_lowering_parses_to_its_own_atoms` pins it. Under `B`, `G r` becomes `B R r`, `F r` becomes `!B U r`, `X r` becomes `B | X r`, `F[0,n] r` becomes `F[0,n] r | F[0,n-1] B`, `G[0,n] r` becomes `G[0,n] r | (B R r)`, `r W s` (until) becomes `(r W s) | (B R r)`, and `r R !s` (before) becomes `(r | B) R !s`. The continual wrapper `G(c -> body)` becomes `B R (c -> body)`, and the trigger wrapper also conjoins `!B` into its rising edge. The three `only` scopes apply the dual scope's wrapper to the De Morgan dual of the body. For until and before the dual is FRET's pairing, `before s` over `!r` for `until s` and back, which is not the logical complement on an unbounded interval: `!(r W s)` and `(!r) R (!s)` differ. @@ -16,7 +16,9 @@ The lowering is in `src/requirement.cpp`. Each scope adds an outer wrapper and a **An output mode gives the system a gutting move.** `G !mode` implies every `In`-scoped guarantee on that mode, and holding the mode at t=0 discharges every `Before`-scoped one. FRET specifications need the output side anyway, since the ventilator's controller sets its own operating mode (`CONT1`, `CONT46`), and there the requirements that drive the mode are what block the move. Nothing in the search stops a repair from weakening those requirements and then exploiting the move, so repairs of a specification with output modes need checking for it. -**A mode is an atom of the lowered formula that sits in no `Formula` field, and the counting path had to be told.** `count_joint_atoms` (`src/fitness/transfer_matrix.cpp`) once left the mode out of `n_total_atoms`, so `free_count` in `count_guard_models` wrapped on `std::size_t` and `mul_pow2` hit the overflow assertion. It is asserted rather than clamped, since a wrong free count is a wrong trace count nothing else catches. Any future field carrying an atom outside `m_condition`/`m_response` meets the same trap. +**A mode is an atom of the lowered formula that sits in no `Formula` field, and the counting path had to be told.** `count_joint_atoms` (`src/fitness/transfer_matrix.cpp`) once left the mode out of `n_total_atoms`, so `free_count` in `count_guard_models` wrapped on `std::size_t` and `mul_pow2` hit the overflow assertion. It is asserted rather than clamped, since a wrong free count is a wrong trace count nothing else catches. Any future field carrying an atom outside `m_condition`/`m_response` meets the same trap, and a formula mode adds each of its atoms through `scope_mode_atoms`. + +**A mode may be a propositional formula, such as `in (pcv_mode | psv_mode)`.** `Scope::m_mode` stays a string. A bare mode is one signal name (`is_bare_mode`), must be in `modes`, and lowers, hashes and serialises exactly as before formula modes, so no golden moved. A formula mode is held in `Formula::to_string` spelling, `(pcv_mode) | (psv_mode)`, which `canonical_mode` gives it at load, so one formula has one string however its source was bracketed. Each of its atoms must be in `modes`, `in_atoms` or `out_atoms`, and a temporal or malformed one is rejected at load. The lowering brackets it wherever the templates place the mode (`mode_operand` in `src/requirement.cpp`), so it is the bare-mode lowering with the formula substituted, which `test_formula_mode_lowering_substitutes_the_formula` pins; `add_atom_prefix` tags every atom inside it. A pure mode that occurs only inside formulas is still in `modes`, so `environment_signals()` still puts it on the input side, and a formula mode is never itself in `modes`: no scope move onto a Global requirement draws it, and a move between scoped kinds carries it unchanged, as it carries a bare mode. The similarity scope term and the implication check compare the mode string, so two formula modes are the same mode only when their canonical strings are equal; `scripts/import_fret.py` sorts each chain of `&` and `|`, so `a | b` and `b | a` import as one. On the ventilator's 11 formula-mode requirements, PEREDUR's LTL is equivalent under `ltlfilt` to FRET's `ftExpanded` at ordinal ticks. Before 2026-11-24 the importer named each formula mode by a fresh output atom with a non-weakenable definition `G(atom <-> formula)`; the realisability verdict is the same either way, since the system can always set the atom to the formula's value, but the fresh atoms joined the mutation pool, the similarity term saw a formula mode and its operands as unrelated modes, and the atoms counted as free wherever a count left out the definition. **No mode axiom is generated.** FRET keeps mode exclusivity in variable definitions the `formalize` path never sees, so it is written as an ordinary non-weakenable requirement, as in `examples/fsm-combined/spec.json`. diff --git a/examples/README.md b/examples/README.md index 94823d51..95ca26ad 100644 --- a/examples/README.md +++ b/examples/README.md @@ -48,6 +48,6 @@ Some ideals in `fixes/` are the reference repairs from the AuRUS repository, and | `liquid-mixer` | The liquid mixer of Mavridou et al. (FM 2021), Table 1. | | `rad` | The Robot-Assisted Dressing case study of the CRADLE project ([cradlerobotics/RAD](https://github.com/cradlerobotics/RAD), commit `5ab8545`), from Chakraborty, Rafiq, Taylor and Farrell, "Plenty to FRET About: From Hazard Analysis to Formal Requirements for Robot-Assisted Dressing" (FMAS 2026), which formalises the requirements of Taylor et al., "All Dressed Up: Requirements for Human-Robot Teamwork" (ISoLA 2026). Five of its six FRET project exports are imported. | | `valu3s-uc6` | The FRET project "VALU3S Use Case 6" (an agricultural robot), built to demonstrate Mu-FRET (Luckcuck, Sheridan, Farrell and Monahan, "Mu-FRET: A Catalogue and Tool for Requirement Refactoring", SoSyM 2026). It was imported from a private copy; the same set is public as `UseCase6.json` in [valu3s-mu/FRETISH-requirements](https://github.com/valu3s-mu/FRETISH-requirements). | -| `ventilator-controller` | The Controller component of the FRET project "Ventilator v0.6.1", from Farrell, Luckcuck, Monahan, Reynolds and Sheridan, "FRETting and Formal Modelling: A Mechanical Lung Ventilator" (ABZ 2024). | +| `ventilator-controller` | The Controller component of the FRET project "Ventilator v0.6.1", from Farrell, Luckcuck, Monahan, Reynolds and Sheridan, "FRETting and Formal Modelling: A Mechanical Lung Ventilator" (ABZ 2024). Its 11 formula-mode scopes, such as `in (PCVMode \| PSVMode)`, are formula modes; before 2026-11-24 each was a fresh `mode_*` output atom with a definition guarantee, which gave 68 guarantees and 63 outputs where there are now 58 and 53. | The FRET exports were converted with `scripts/import_fret.py`, whose docstring lists every conversion rule. diff --git a/examples/ventilator-controller/spec.json b/examples/ventilator-controller/spec.json index 42c9c7b5..f03478af 100644 --- a/examples/ventilator-controller/spec.json +++ b/examples/ventilator-controller/spec.json @@ -115,7 +115,7 @@ }, "scope": { "type": "In", - "mode": "mode_psv_mode_and_inspiratory_pause_button" + "mode": "(inspiratory_pause_button) & (psv_mode)" } }, { @@ -127,7 +127,7 @@ }, "scope": { "type": "In", - "mode": "mode_start_up_mode_or_standby_mode" + "mode": "(standby_mode) | (start_up_mode)" } }, { @@ -139,7 +139,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_or_psv_mode" + "mode": "(pcv_mode) | (psv_mode)" } }, { @@ -209,7 +209,7 @@ }, "scope": { "type": "In", - "mode": "mode_psv_mode_and_rm_button" + "mode": "(psv_mode) & (rm_button)" } }, { @@ -235,7 +235,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_and_inspiratory_pause_button" + "mode": "(inspiratory_pause_button) & (pcv_mode)" } }, { @@ -268,7 +268,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_or_psv_mode" + "mode": "(pcv_mode) | (psv_mode)" } }, { @@ -316,7 +316,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_or_psv_mode_and_rm_button_and_not_inspiratory_pause_button" + "mode": "((!(inspiratory_pause_button)) & ((pcv_mode) | (psv_mode))) & (rm_button)" } }, { @@ -340,7 +340,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_and_rm_button" + "mode": "(pcv_mode) & (rm_button)" } }, { @@ -352,7 +352,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_or_psv_mode_and_expiratory_pause_button" + "mode": "((pcv_mode) | (psv_mode)) & (expiratory_pause_button)" } }, { @@ -388,7 +388,7 @@ }, "scope": { "type": "In", - "mode": "mode_pcv_mode_or_psv_mode_and_inspiratory_pause_button" + "mode": "((pcv_mode) | (psv_mode)) & (inspiratory_pause_button)" } }, { @@ -595,7 +595,7 @@ }, "scope": { "type": "In", - "mode": "mode_psv_mode_and_expiratory_phase" + "mode": "(expiratory_phase) & (psv_mode)" } }, { @@ -662,96 +662,6 @@ "mode": "final_state" } }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_pcv_mode_and_inspiratory_pause_button <-> (pcv_mode & inspiratory_pause_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_pcv_mode_and_rm_button <-> (pcv_mode & rm_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_pcv_mode_or_psv_mode <-> (pcv_mode | psv_mode)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_pcv_mode_or_psv_mode_and_expiratory_pause_button <-> (( pcv_mode | psv_mode ) & expiratory_pause_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_pcv_mode_or_psv_mode_and_inspiratory_pause_button <-> (( pcv_mode | psv_mode ) & inspiratory_pause_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_pcv_mode_or_psv_mode_and_rm_button_and_not_inspiratory_pause_button <-> (( pcv_mode | psv_mode ) & rm_button & ! inspiratory_pause_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_psv_mode_and_expiratory_phase <-> (psv_mode & expiratory_phase)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_psv_mode_and_inspiratory_pause_button <-> (psv_mode & inspiratory_pause_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_psv_mode_and_rm_button <-> (psv_mode & rm_button)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, - { - "condition": "true", - "condition-type": "continual", - "response": "mode_start_up_mode_or_standby_mode <-> (start_up_mode | standby_mode)", - "timing": { - "type": "Always" - }, - "weakenable": false - }, { "condition": "true", "condition-type": "continual", @@ -829,16 +739,6 @@ "min_expiratory_time_eq_insp_clock_div_2", "min_expiratory_time_ge_0p4", "min_expiratory_time_le_2", - "mode_pcv_mode_and_inspiratory_pause_button", - "mode_pcv_mode_and_rm_button", - "mode_pcv_mode_or_psv_mode", - "mode_pcv_mode_or_psv_mode_and_expiratory_pause_button", - "mode_pcv_mode_or_psv_mode_and_inspiratory_pause_button", - "mode_pcv_mode_or_psv_mode_and_rm_button_and_not_inspiratory_pause_button", - "mode_psv_mode_and_expiratory_phase", - "mode_psv_mode_and_inspiratory_pause_button", - "mode_psv_mode_and_rm_button", - "mode_start_up_mode_or_standby_mode", "monitor_inhale_trigger", "off", "out_of_service_warning", @@ -869,16 +769,6 @@ "fail_safe_mode", "final_state", "inspiratory_phase", - "mode_pcv_mode_and_inspiratory_pause_button", - "mode_pcv_mode_and_rm_button", - "mode_pcv_mode_or_psv_mode", - "mode_pcv_mode_or_psv_mode_and_expiratory_pause_button", - "mode_pcv_mode_or_psv_mode_and_inspiratory_pause_button", - "mode_pcv_mode_or_psv_mode_and_rm_button_and_not_inspiratory_pause_button", - "mode_psv_mode_and_expiratory_phase", - "mode_psv_mode_and_inspiratory_pause_button", - "mode_psv_mode_and_rm_button", - "mode_start_up_mode_or_standby_mode", "pcv_mode", "psv_mode", "rm", diff --git a/include/requirement.hpp b/include/requirement.hpp index bbbbb155..21dac821 100644 --- a/include/requirement.hpp +++ b/include/requirement.hpp @@ -130,11 +130,15 @@ enum class ScopeKind : std::uint8_t { }; /// A scope kind together with the mode it is relative to. `Global` carries an -/// empty mode; every other kind requires one, and that mode must be declared in -/// `Specification::m_modes`. +/// empty mode; every other kind requires one. A bare mode is one signal name, +/// which must be declared in `Specification::m_modes`. A formula mode such as +/// `(a) | (b)` is a propositional formula over declared signals, each in +/// `m_modes`, `m_in_atoms` or `m_out_atoms`, held in `Formula::to_string` +/// spelling (see `canonical_mode`). struct Scope { ScopeKind m_kind = ScopeKind::Global; - /// Name of the mode. Empty exactly when `m_kind` is `Global`. + /// The mode: a signal name or a formula. Empty exactly when `m_kind` is + /// `Global`. std::string m_mode; friend bool operator<(const Scope& lhs, const Scope& rhs); @@ -145,6 +149,21 @@ struct Scope { [[nodiscard]] bool is_global() const { return m_kind == ScopeKind::Global; } }; +/// True when @p mode is a single signal name, the only form a mode took before +/// formula modes. Every bare mode lowers, hashes and serialises as it did then. +bool is_bare_mode(const std::string& mode); + +/// The stored spelling of the mode @p mode: a bare name unchanged, a formula +/// in `Formula::to_string` form, so one formula has one spelling however its +/// source was bracketed. +/// @throws std::invalid_argument when @p mode is neither a name nor a +/// propositional formula. +std::string canonical_mode(const std::string& mode); + +/// Every signal the scope's mode mentions, without the constants: the mode +/// itself when bare, nothing for `Global`. +std::vector scope_mode_atoms(const Scope& scope); + /// True for the three "only" scopes, whose lowering negates the requirement's /// obligation and applies it outside the named interval. bool is_only_scope(ScopeKind kind); diff --git a/include/serialisation.hpp b/include/serialisation.hpp index 30e8d355..63393ebb 100644 --- a/include/serialisation.hpp +++ b/include/serialisation.hpp @@ -143,7 +143,7 @@ inline void from_json(const nlohmann::json& jobj, Scope& scope) { scope.m_kind = kind; scope.m_mode = kind == ScopeKind::Global ? std::string() - : jobj.at("mode").get(); + : canonical_mode(jobj.at("mode").get()); return; } throw std::invalid_argument("unknown scope type: " + type); @@ -367,6 +367,14 @@ inline std::optional validate_scope_json( scope.at("mode").get().empty()) { return path + ".mode: must be a non-empty string"; } + const std::string mode = scope.at("mode").get(); + if (!is_bare_mode(mode)) { + const std::optional formula = Formula::try_parse(mode); + if (!formula || !formula->is_propositional()) { + return path + ".mode: '" + mode + + "' is neither a signal name nor a propositional formula"; + } + } return std::nullopt; } @@ -414,7 +422,9 @@ inline std::optional validate_requirement_json( /// Checks the declared modes against the scopes that use them. A mode may also /// be declared in `in_atoms` or `out_atoms`, and then takes that side (see -/// `Specification::m_modes`). +/// `Specification::m_modes`). A bare mode must be in `modes`; each atom of a +/// formula mode must be in `modes`, `in_atoms` or `out_atoms`, so a pure mode +/// inside a formula is still declared in `modes` and reaches the input side. /// /// This is the one cross-field check in the file. Nothing validates that a /// condition or response mentions only declared atoms, but a scope's mode has @@ -431,6 +441,16 @@ inline std::optional validate_modes_json( return std::find(declared.begin(), declared.end(), name) != declared.end(); }; + std::vector signals = declared; + for (const char* field : {"in_atoms", "out_atoms"}) { + if (jobj.contains(field)) { + const auto atoms = jobj.at(field).get>(); + signals.insert(signals.end(), atoms.begin(), atoms.end()); + } + } + const auto is_signal = [&signals](const std::string& name) { + return std::find(signals.begin(), signals.end(), name) != signals.end(); + }; for (const char* field : {"assumptions", "guarantees"}) { const nlohmann::json& reqs = jobj.at(field); for (std::size_t i = 0; i < reqs.size(); ++i) { @@ -439,9 +459,21 @@ inline std::optional validate_modes_json( continue; } const auto mode = req.at("scope").at("mode").get(); - if (!is_declared(mode)) { - return std::string(field) + "[" + std::to_string(i) + - "].scope.mode: '" + mode + "' is not declared in modes"; + const std::string where = std::string(field) + "[" + + std::to_string(i) + "].scope.mode: '"; + if (is_bare_mode(mode)) { + if (!is_declared(mode)) { + return where + mode + "' is not declared in modes"; + } + continue; + } + const Scope scope{ScopeKind::In, canonical_mode(mode)}; + for (const std::string& atom : scope_mode_atoms(scope)) { + if (!is_signal(atom)) { + return where + atom + + "' in a formula mode is not declared in modes, " + "in_atoms or out_atoms"; + } } } } diff --git a/schemas/specification.schema.json b/schemas/specification.schema.json index 31d81926..61ce2e5e 100644 --- a/schemas/specification.schema.json +++ b/schemas/specification.schema.json @@ -85,7 +85,7 @@ ] }, "mode": { - "description": "Name of the mode, which must appear in the specification's modes list. Required for every type but Global, and forbidden for Global.", + "description": "The mode: a signal name, which must appear in the specification's modes list, or a propositional formula (such as \"pcv_mode | psv_mode\") whose every atom appears in modes, in_atoms or out_atoms. Required for every type but Global, and forbidden for Global.", "type": "string", "minLength": 1 } diff --git a/scripts/import_fret.py b/scripts/import_fret.py index 5ba298c5..97cfc0ec 100755 --- a/scripts/import_fret.py +++ b/scripts/import_fret.py @@ -26,10 +26,10 @@ - `=>` becomes `->`, and `TRUE`/`FALSE` become `true`/`false`. - Names become snake_case, since SPOT mishandles uppercase inputs, and `%` becomes `_pct`: `measureO2%` is `measure_o2_pct`. -- A scope keeps its kind and mode. A formula mode such as `in (a | b)` gets - a fresh output atom, `mode_a_or_b`, defined by a non-weakenable guarantee - `G(mode_a_or_b <-> (a | b))`. The definition is exact: the system sees each - step's inputs before it chooses its outputs. +- A scope keeps its kind and mode. A formula mode such as `in (b | a)` stays + a formula, written as PEREDUR stores it, `(a) | (b)`: operands bracketed + and each chain of `&` or `|` sorted, so one formula has one spelling. Its + atoms are read, like a condition's, and are not added to `modes`. - A mode that a requirement also mentions, such as one the controller sets, is declared as an atom too and takes that atom's side. A mode only scopes name is a pure mode, which PEREDUR reads as an input, unless an Output @@ -147,6 +147,77 @@ def strip_parens(expr): return expr +def canonical_mode(formula, reqid): + """`formula`, a propositional formula over `&`, `|`, `!` and brackets, + in the spelling PEREDUR stores a formula mode in (`Formula::to_string`): + every operand bracketed, `!(x)`, `(x) & (y)`. The operands of a chain of + `&` or `|` are sorted, so `a | b` and `b | a` give one string.""" + toks = re.findall(r"[A-Za-z_][A-Za-z0-9_]*|[&|!()]|\S", formula) + pos = 0 + + def peek(): + return toks[pos] if pos < len(toks) else None + + def take(expected=None): + nonlocal pos + tok = peek() + if tok is None or (expected and tok != expected): + raise FretImportError(f"{reqid}: cannot read formula mode " + f"{formula!r}") + pos += 1 + return tok + + def chain(op, operand): + kids = [operand()] + while peek() == op: + take(op) + kids.append(operand()) + return ("chain", op, kids) if len(kids) > 1 else kids[0] + + def disj(): + return chain("|", conj) + + def conj(): + return chain("&", neg) + + def neg(): + if peek() == "!": + take("!") + return ("not", neg()) + if peek() == "(": + take("(") + node = disj() + take(")") + return node + tok = take() + if not IDENT.fullmatch(tok): + raise FretImportError(f"{reqid}: unsupported operator {tok!r} " + f"in formula mode {formula!r}") + return ("atom", tok) + + def flatten(node, op): + if node[0] == "chain" and node[1] == op: + return [leaf for k in node[2] for leaf in flatten(k, op)] + return [node] + + def render(node): + if node[0] == "atom": + return node[1] + if node[0] == "not": + return f"!({render(node[1])})" + op = node[1] + parts = sorted(render(k) for k in flatten(node, op)) + out = parts[0] + for part in parts[1:]: + out = f"({out}) {op} ({part})" + return out + + tree = disj() + if peek() is not None: + raise FretImportError(f"{reqid}: cannot read formula mode {formula!r}") + return render(tree) + + class Node: """A parsed subexpression spanning tokens [lo, hi).""" @@ -292,8 +363,6 @@ def __init__(self, atomise=False, from_fulltext=(), skip=(), self.labels = collections.defaultdict(set) self.roles = collections.defaultdict(set) self.modes = set() - # Each formula mode's fresh atom, mapped to the formula it names. - self.defined = {} self.original = {} self.notes = collections.defaultdict(list) self.atomise, self.merge_case = atomise, merge_case @@ -479,30 +548,17 @@ def scope(self, s, reqid): if SCOPES[kind] is None: return None mode = self.formula(s["scope_mode"], reqid) - if not IDENT.fullmatch(mode): - mode = self.define(mode, reqid) - self.modes.add(mode) - return {"type": SCOPES[kind], "mode": mode} - - def define(self, formula, reqid): - """A fresh output atom naming the formula mode `formula`. - - Its definition `G(name <-> formula)` is exact as a guarantee: the - system sees each step's inputs before it chooses its outputs, so it - can always match the formula, and can never do otherwise. - """ - words = re.sub(r"\s+", "_", formula.replace("|", " or ") - .replace("&", " and ").replace("!", " not ") - .replace("(", " ").replace(")", " ")).strip("_") - name = f"mode_{words}" - if self.defined.get(name, formula) != formula or name in self.original: - raise FretImportError(f"{reqid}: formula mode {formula!r} would " - f"be named {name!r}, which is taken") - self.defined[name] = formula - for a in set(IDENT.findall(formula)) - LITERALS: + if IDENT.fullmatch(mode): + self.modes.add(mode) + return {"type": SCOPES[kind], "mode": mode} + # A formula mode stays a formula. Its atoms are read like a + # condition's, so they are atoms with a side, and need no entry in + # `modes`. + canonical = canonical_mode(mode, reqid) + for a in set(IDENT.findall(mode)) - LITERALS: self.roles[a].add("read") - self.notes["formula mode"].append(f"{reqid}: {formula} -> {name}") - return name + self.notes["formula mode"].append(f"{reqid}: {canonical}") + return {"type": SCOPES[kind], "mode": canonical} def fields(self, r, component): """The FRET fields of `r` to convert, or None to leave `r` out.""" @@ -606,10 +662,6 @@ def label(self, v): self.labels[self.atom(v["variable_name"])].add(v["idType"]) def partition(self, force_in, force_out): - taken = set(self.defined) & set(self.original) - if taken: - raise FretImportError(f"formula mode names {sorted(taken)} are " - f"also FRET names") def forced(a, patterns): return any(fnmatch.fnmatchcase(a, pat) for pat in patterns) @@ -658,11 +710,11 @@ def settle(v, output): # already reads as an input, unless a label or a flag makes it an # output. Declaring it an input atom as well would change nothing # but let mutation draw it into conditions and responses. - for m in sorted(self.modes - set(self.roles) - set(self.defined)): + for m in sorted(self.modes - set(self.roles)): if side(m): outs.append(m) self.notes["mode made an output by label or flag"].append(m) - return ins, sorted(outs + list(self.defined)) + return ins, sorted(outs) def shared_side(self, atom, names, side, forced, force_in, force_out): """The side of a comparison over several variables, which only its @@ -1105,9 +1157,6 @@ def load(paths, component, force_in, force_out, all_components=False, {conv.atom(a) for a in force_out}) spec = {"assumptions": [], "guarantees": conv.guarantees, "in_atoms": ins, "out_atoms": outs} - for name, formula in sorted(conv.defined.items()): - spec["guarantees"].append(always(f"{name} <-> ({formula})")) - conv.reqids.append(["mode definition"]) for group in exclusive: names = sorted({conv.atom(n.strip()) for n in group.split(",") if n.strip()}) diff --git a/scripts/test_import_fret.py b/scripts/test_import_fret.py index fe60e0e4..80334387 100644 --- a/scripts/test_import_fret.py +++ b/scripts/test_import_fret.py @@ -442,23 +442,22 @@ def rejects_with(export, fragment, msg, **kw): spec, conv = load({"requirements": scoped, "variables": [var("labelledMode", "Output"), var("pureMode", "Input")]}) -check(spec["guarantees"][0]["scope"], {"type": "In", "mode": "mode_a_or_b"}, - "a formula mode is named by a fresh atom") -check(spec["guarantees"][-1], {"condition": "true", - "condition-type": "continual", - "response": "mode_a_or_b <-> (a | b)", - "timing": {"type": "Always"}, - "weakenable": False}, - "the fresh atom's definition is a non-weakenable guarantee") -check(conv.reqids[-1], ["mode definition"], "--ids names the definition") -check(spec["modes"], ["labelled_mode", "mode_a_or_b", "pure_mode", - "standby_mode"], "every scope's mode is declared") -check({"mode_a_or_b", "standby_mode", "labelled_mode"} - <= set(spec["out_atoms"]), True, - "the fresh atom, a mode a response sets and a mode labelled Output are " - "outputs") +check(spec["guarantees"][0]["scope"], {"type": "In", "mode": "(a) | (b)"}, + "a formula mode stays a formula, in PEREDUR's spelling") +check(len(spec["guarantees"]), len(scoped), + "a formula mode adds no definition guarantee") +check(spec["modes"], ["labelled_mode", "pure_mode", "standby_mode"], + "every bare scope mode is declared, and a formula mode is not") +check({"standby_mode", "labelled_mode"} <= set(spec["out_atoms"]), True, + "a mode a response sets and a mode labelled Output are outputs") check({"a", "b"} <= set(spec["in_atoms"]), True, "a formula mode's atoms are read, so inputs by the role rule") +check(I.canonical_mode("c & (b | a) & !d", "T"), + "((!(d)) & ((a) | (b))) & (c)", + "a formula mode's chains are flattened and sorted") +check(I.canonical_mode("(a | b) | c", "T"), + I.canonical_mode("c | (b | a)", "T"), + "one formula mode has one spelling however it is bracketed") check("pure_mode" in spec["in_atoms"] + spec["out_atoms"], False, "a mode only scopes name stays a pure mode, even labelled Input") check(spec["guarantees"][4]["scope"], {"type": "After", @@ -466,12 +465,14 @@ def rejects_with(export, fragment, msg, **kw): "after keeps its kind") check(spec["guarantees"][4]["response"], "measure_o2_pct & y", "% in a name becomes _pct") -rejects_with({"requirements": [ +spec, _ = load({"requirements": [ req("G1", scope={"type": "in"}, scope_mode="((a | b) & c)", timing="always", post_condition="(x)"), req("G2", scope={"type": "in"}, scope_mode="(a | (b & c))", - timing="always", post_condition="(y)")], "variables": []}, - "which is taken", "two groupings with one fresh name are rejected") + timing="always", post_condition="(y)")], "variables": []}) +check([g["scope"]["mode"] for g in spec["guarantees"]], + ["((a) | (b)) & (c)", "((b) & (c)) | (a)"], + "two groupings of one set of atoms stay two formula modes") spec, conv = load({"requirements": scoped, "variables": [var("labelledMode", "Output")]}, diff --git a/src/fitness/transfer_matrix.cpp b/src/fitness/transfer_matrix.cpp index abf719b1..21922f80 100644 --- a/src/fitness/transfer_matrix.cpp +++ b/src/fitness/transfer_matrix.cpp @@ -60,9 +60,11 @@ std::size_t count_joint_atoms(const Requirement& req1, // error in the count: the mode still reaches the automaton's atomic // propositions, so n_mentioned in count_guard_models exceeds n_total_atoms // and its unsigned subtraction wraps. + // A formula mode adds each of its atoms, which is what reaches the + // automaton, rather than its spelling. const auto add_mode = [&atoms](const Requirement& req) { - if (!req.m_scope.is_global()) { - atoms.insert(req.m_scope.m_mode); + for (const std::string& atom : scope_mode_atoms(req.m_scope)) { + atoms.insert(atom); } }; add_mode(req1); diff --git a/src/requirement.cpp b/src/requirement.cpp index a8945da2..64aa556a 100644 --- a/src/requirement.cpp +++ b/src/requirement.cpp @@ -2,11 +2,14 @@ #include #include +#include #include #include #include +#include #include #include +#include #include #include #include @@ -267,6 +270,13 @@ std::string negated_timing_body(const Timing& timing, return timing_body(dual_timing(timing), negated, boundary); } +// The mode as an operand of the scope templates. A bare name stands alone, so +// every bare-mode lowering is the string it always was; a formula mode is +// bracketed, since the templates place the mode beside `&`, `->` and `X`. +std::string mode_operand(const std::string& mode) { + return is_bare_mode(mode) ? mode : "(" + mode + ")"; +} + // The boundary marker whose truth ends the scope's interval, or the empty // string where the interval runs to the end of the trace and nothing is ever // discharged early. @@ -278,11 +288,11 @@ std::string scope_boundary(const Scope& scope) { return ""; case ScopeKind::In: case ScopeKind::OnlyAfter: - return end_of_mode(scope.m_mode); + return end_of_mode(mode_operand(scope.m_mode)); case ScopeKind::NotIn: case ScopeKind::Before: case ScopeKind::OnlyIn: - return start_of_mode(scope.m_mode); + return start_of_mode(mode_operand(scope.m_mode)); } assert(false); __builtin_unreachable(); @@ -291,7 +301,7 @@ std::string scope_boundary(const Scope& scope) { // Places the conditioned obligation @p inner at the start of the scope's // interval, and at every later re-entry where the interval repeats. std::string scope_wrap(const Scope& scope, const std::string& inner) { - const std::string& mode = scope.m_mode; + const std::string mode = mode_operand(scope.m_mode); const std::string som = start_of_mode(mode); const std::string eom = end_of_mode(mode); switch (scope.m_kind) { @@ -394,6 +404,44 @@ bool operator==(const Scope& lhs, const Scope& rhs) { return lhs.m_kind == rhs.m_kind && lhs.m_mode == rhs.m_mode; } +bool is_bare_mode(const std::string& mode) { + return !mode.empty() && std::all_of(mode.begin(), mode.end(), [](char chr) { + return std::isalnum(static_cast(chr)) != 0 || chr == '_'; + }); +} + +std::string canonical_mode(const std::string& mode) { + if (is_bare_mode(mode)) { + return mode; + } + const std::optional formula = Formula::try_parse(mode); + if (!formula || !formula->is_propositional()) { + throw std::invalid_argument("scope mode '" + mode + + "' is neither a signal name nor a " + "propositional formula"); + } + return formula->to_string(); +} + +std::vector scope_mode_atoms(const Scope& scope) { + if (scope.is_global()) { + return {}; + } + if (is_bare_mode(scope.m_mode)) { + return {scope.m_mode}; + } + std::unordered_set found; + collect_atoms(Formula(scope.m_mode), found); + std::vector atoms; + for (const std::string& name : found) { + if (!is_constant_atom(name)) { + atoms.push_back(name); + } + } + std::sort(atoms.begin(), atoms.end()); + return atoms; +} + bool is_only_scope(ScopeKind kind) { return kind == ScopeKind::OnlyIn || kind == ScopeKind::OnlyBefore || kind == ScopeKind::OnlyAfter; @@ -734,7 +782,12 @@ Scope rewrite_scope_mode( if (scope.is_global()) { return scope; } - return Scope{scope.m_kind, transform(scope.m_mode)}; + if (is_bare_mode(scope.m_mode)) { + return Scope{scope.m_kind, transform(scope.m_mode)}; + } + return Scope{ + scope.m_kind, + rewrite_atom_names(Formula(scope.m_mode), transform).to_string()}; } // A stop condition is a formula over the specification's atoms, tagged like the @@ -862,26 +915,27 @@ std::string to_string(ConditionType condition_type) { } std::string to_string(const Scope& scope) { + const std::string mode = mode_operand(scope.m_mode); switch (scope.m_kind) { case ScopeKind::Global: return ""; case ScopeKind::In: - return "in " + scope.m_mode; + return "in " + mode; // FRET's grammar spells this one "except in" (or "unless in", or "when // not in"). A bare "not in" is a parse error there, so the internal // NotIn name and the FRETish text deliberately differ. case ScopeKind::NotIn: - return "except in " + scope.m_mode; + return "except in " + mode; case ScopeKind::Before: - return "before " + scope.m_mode; + return "before " + mode; case ScopeKind::After: - return "after " + scope.m_mode; + return "after " + mode; case ScopeKind::OnlyIn: - return "only in " + scope.m_mode; + return "only in " + mode; case ScopeKind::OnlyBefore: - return "only before " + scope.m_mode; + return "only before " + mode; case ScopeKind::OnlyAfter: - return "only after " + scope.m_mode; + return "only after " + mode; } assert(false); __builtin_unreachable(); diff --git a/test/fitness/transfer_matrix_tests.cpp b/test/fitness/transfer_matrix_tests.cpp index 9e3f5f5c..c6f1105e 100644 --- a/test/fitness/transfer_matrix_tests.cpp +++ b/test/fitness/transfer_matrix_tests.cpp @@ -506,4 +506,23 @@ TEST(test_count_traces_rounds_faithfully_above_64_bits) { } #endif +// A formula mode's atoms reach the automaton one by one, so the count must +// take them one by one. Counting the mode's spelling as a single atom leaves +// n_mentioned above n_total_atoms, and count_guard_models asserts. +TEST(test_formula_mode_atoms_are_counted) { + const Requirement req(Formula("c"), Formula("x"), timing::always(), + ConditionType::Continual, /*weakenable=*/true, + /*removed=*/false, + Scope{ScopeKind::In, canonical_mode("p & q")}); + expect(count_joint_atoms(req, req) == 4, + "count_joint_atoms: c, x, p and q make four atoms, got " + + std::to_string(count_joint_atoms(req, req))); + const std::size_t steps = 3; + const Count traces = count_traces(transfer_system_for(req), steps); + expect(std::isfinite(traces) && traces > 0 && + traces < exact_power_of_two(4 * static_cast(steps)), + "count_traces: a formula-mode requirement must count some, not " + "all, traces over its four atoms"); +} + } // namespace diff --git a/test/scope_tests.cpp b/test/scope_tests.cpp index 77261f8d..7652fc81 100644 --- a/test/scope_tests.cpp +++ b/test/scope_tests.cpp @@ -910,4 +910,77 @@ TEST(test_requirement_implies_trigger_condition_at_coincidence) { "requirement_implies: a trigger condition away from a " "coincidence must stay unproved"); } + +// Replaces every occurrence of @p target in @p text with @p replacement. +std::string replace_all(std::string text, const std::string& target, + const std::string& replacement) { + for (std::size_t at = text.find(target); at != std::string::npos; + at = text.find(target, at + replacement.size())) { + text.replace(at, target.size(), replacement); + } + return text; +} + +// A formula mode lowers to the bare-mode lowering with the formula, bracketed, +// in place of the mode. The bare mode `zmode` occurs in no other atom, so a +// plain text replacement is exact. +TEST(test_formula_mode_lowering_substitutes_the_formula) { + const std::string formula = canonical_mode("p | (q & !r)"); + for (const ScopeCase& scope_case : scope_cases()) { + if (scope_case.m_kind == ScopeKind::Global) { + continue; + } + for (const Timing& timing : timing_cases()) { + for (const ConditionType ctype : + {ConditionType::Trigger, ConditionType::Continual}) { + const auto lower = [&](const std::string& mode) { + return Requirement(Formula("c"), Formula("x"), timing, + ctype, /*weakenable=*/true, + /*removed=*/false, + Scope{scope_case.m_kind, mode}); + }; + const Requirement bare = lower("zmode"); + const Requirement over_formula = lower(formula); + expect(over_formula.m_ltl == replace_all(bare.m_ltl, "zmode", + "(" + formula + ")"), + std::string("scope: a formula mode must lower as the " + "bare mode with the formula substituted, " + "under ") + + scope_case.m_name + ": " + over_formula.m_ltl); + } + } + } +} + +TEST(test_atom_prefix_reaches_formula_mode_atoms) { + const Requirement req(Formula("c"), Formula("x"), timing::always(), + ConditionType::Continual, /*weakenable=*/true, + /*removed=*/false, + Scope{ScopeKind::In, canonical_mode("p | !q")}); + const Requirement tagged = add_atom_prefix(req); + const std::string prefix(k_atom_prefix); + expect( + tagged.m_scope.m_mode == "(" + prefix + "p) | (!(" + prefix + "q))", + "scope: add_atom_prefix must tag every atom of a formula mode, got " + + tagged.m_scope.m_mode); + expect(scope_mode_atoms(tagged.m_scope) == + std::vector{prefix + "p", prefix + "q"}, + "scope: the tagged formula mode must name the tagged atoms"); + expect(strip_atom_prefix(tagged) == req, + "scope: strip_atom_prefix must invert the tagging of a formula " + "mode"); +} + +TEST(test_bare_mode_is_unchanged_by_canonical_mode) { + for (const char* mode : {"m", "standby_mode", "Grant"}) { + expect( + is_bare_mode(mode) && canonical_mode(mode) == mode, + std::string("scope: a bare mode must keep its spelling: ") + mode); + expect(scope_mode_atoms(Scope{ScopeKind::In, mode}) == + std::vector{mode}, + std::string("scope: a bare mode is its own one atom: ") + mode); + } + expect(!is_bare_mode("a | b") && !is_bare_mode(""), + "scope: a formula and the empty string are not bare modes"); +} } // namespace diff --git a/test/serialisation_tests.cpp b/test/serialisation_tests.cpp index 1c09fdaf..eb97bebb 100644 --- a/test/serialisation_tests.cpp +++ b/test/serialisation_tests.cpp @@ -579,4 +579,53 @@ TEST(test_scoped_requirement_needs_a_mode) { "be rejected"); } +nlohmann::json formula_mode_spec(const std::string& mode, + const std::vector& modes) { + return {{"assumptions", nlohmann::json::array()}, + {"guarantees", + {{{"condition", "a"}, + {"condition-type", "continual"}, + {"response", "b"}, + {"timing", {{"type", "Immediately"}}}, + {"scope", {{"type", "In"}, {"mode", mode}}}}}}, + {"in_atoms", {"a", "p"}}, + {"out_atoms", {"b", "q"}}, + {"modes", modes}}; +} + +TEST(test_formula_mode_atoms_must_be_declared) { + expect(!validate_specification_json(formula_mode_spec("p | q & !m", {"m"})) + .has_value(), + "validate_specification_json: a formula mode over an input, an " + "output and a declared mode must be accepted"); + const auto err = + validate_specification_json(formula_mode_spec("p | z", {})); + expect(err.has_value() && err->find("'z'") != std::string::npos, + "validate_specification_json: a formula mode over an undeclared " + "atom must be rejected, naming it"); + expect(validate_specification_json(formula_mode_spec("p | F q", {})) + .has_value(), + "validate_specification_json: a temporal formula mode must be " + "rejected"); + expect( + validate_specification_json(formula_mode_spec("p |", {})).has_value(), + "validate_specification_json: a malformed formula mode must be " + "rejected"); +} + +TEST(test_formula_mode_loads_in_one_spelling) { + const Specification spec = + formula_mode_spec("((p | q))", {}).get(); + expect(spec.m_guarantees.at(0).m_scope.m_mode == "(p) | (q)", + "from_json(Scope): a formula mode must load in Formula::to_string " + "spelling, got " + + spec.m_guarantees.at(0).m_scope.m_mode); + const nlohmann::json written = spec; + expect(written.at("guarantees").at(0).at("scope").at("mode") == "(p) | (q)", + "to_json(Scope): a formula mode must be written without the atom " + "prefix"); + expect(written.get() == spec, + "a formula mode must round-trip"); +} + } // namespace From 0d0c48229f217ccd329bc0a98929d2b4987afa95 Mon Sep 17 00:00:00 2001 From: benmandrew Date: Tue, 24 Nov 2026 18:49:34 +0000 Subject: [PATCH 2/2] test(drivers): aim the crash-report signal at the main thread The crash-report test sent SIGSEGV with kill() right after the run printed "Seed: 7". Starting the search lazily builds the global thread pool. glibc blocks every signal in the thread that calls pthread_create, so the new worker starts with the signal unblocked, and a process-directed signal can land on it before TSan has attached that thread. TSan then aborts with "CHECK failed: tsan_interceptors_posix.cpp:2184 ((thr->slot)) != (0)". Send the signal to the main thread with tgkill() instead. The main thread holds it pending until it unblocks signals, so the handler still runs on a thread TSan knows. tgkill is Linux-only, so other platforms keep kill(). Measured locally under TSan: 7 of 40 runs failed before this change and 0 of 30 failed after it. --- test/drivers/e2e_tests.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/test/drivers/e2e_tests.cpp b/test/drivers/e2e_tests.cpp index fa708dac..e82b50b7 100644 --- a/test/drivers/e2e_tests.cpp +++ b/test/drivers/e2e_tests.cpp @@ -1,6 +1,10 @@ #include #include +#ifdef __linux__ +#include +#endif + #include #include #include @@ -1503,7 +1507,15 @@ TEST_IN("driver_peredur", test_peredur_writes_a_crash_report) { read_until_marker(child.m_read_fd, "Seed: 7\n"); expect(contains(announced, "Seed: 7\n"), "peredur: the endless run reached its search"); + // The search builds the thread pool as it starts. glibc blocks every + // signal in the thread calling pthread_create, so a process-directed + // signal lands on the new worker, and TSan aborts on a thread it has not + // yet attached. The main thread holds the signal pending until it unblocks. +#ifdef __linux__ + syscall(SYS_tgkill, child.m_pid, child.m_pid, SIGSEGV); +#else kill(child.m_pid, SIGSEGV); +#endif const std::pair read = read_until_eof(child.m_read_fd, k_deadline);