Skip to content

Fix time_slave missing config validation - #332

Open
mattday-etas wants to merge 7 commits into
eclipse-score:mainfrom
etas-contrib:fix-missing-config-validation
Open

mattday-etas wants to merge 7 commits into
eclipse-score:mainfrom
etas-contrib:fix-missing-config-validation

Conversation

@mattday-etas

Copy link
Copy Markdown
Contributor

Description

Closes #314.

The TimeSlave config parser did not check values against time_slave_config_schema.json. Out-of-range values were applied silently. For example, "domain_number": 128 makes the slave ignore every Sync. A JSON boolean was also accepted for an integer field.

The parser now enforces the schema's types, minimum/maximum and additionalProperties: false. It collects every error, and TimeSlave::Initialize logs them and returns kInitFailure. Invalid values are never applied.

Behaviour change: a config file with an unknown or misspelled key, or any invalid value, now stops the TimeSlave from starting. Before, the bad value was ignored or applied. The deployed QNX configs are now validated against the schema in CI, and they pass.

How the parser stays in sync with the schema:

  • config_schema_table.h lists the keys, types and ranges the parser enforces.
  • config_schema_consistency_test compares that table with the schema in both directions. It also checks the schema defaults against the C++ struct defaults. It fails if the schema uses a keyword the parser does not implement (enum, pattern, ...).
  • A static_assert fails the build if a schema range does not fit the C++ field type.

Also:

  • ParseConfig returns ConfigParseResult instead of calling std::abort(). The EXPECT_DEATH tests became plain assertions (about 18 s down to 0.1 s).
  • The configuration guide documents validation and the refuse-to-start behaviour. The stale pdelay_interval_ms name is fixed in the guide and the design docs.

Enforce the schema's min/max ranges for all integer options, reject
JSON booleans for integer fields (and numbers for boolean fields), and
abort on any fatal config error instead of only logging it. Add tests
and document the validation in the configuration guide.

This does not use the schema, but uses manual validation logic to
enforce the same constraints.

Fixes eclipse-score#314
Add a build-time tool that derives keys, ranges and defaults from
time_slave_config_schema.json, so the parser can no longer drift from
the schema. Reject keys the schema doesn't define and fail when the
schema gains a property the parser doesn't handle. Tests now take
defaults and range boundaries from the generated header.
Follow-up to the schema validation for eclipse-score#314. Drop the build-time
generator (tools/gen_config_limits) and its genrule. The parser now uses
a hand-written table in config_limits.h, and a unit test keeps it in
sync with time_slave_config_schema.json.

- config_schema_consistency_test loads the schema and compares it with
  the table in both directions: keys, types, ranges, defaults. It also
  fails on schema keywords the parser does not implement (enum, pattern,
  exclusiveMinimum, ...), on additionalProperties != false, and on a
  non-empty "required".
- Integer properties are passed to the parser as template arguments, so a
  static_assert fails the build if a schema range does not fit the C++
  field type (e.g. domain_number above 255 into uint8_t).
- ParseConfig returns ConfigParseResult instead of calling std::abort().
  It collects all errors, and TimeSlave::Initialize logs them and returns
  kInitFailure. Invalid values are never applied.
- Replace the EXPECT_DEATH tests with plain assertions on the reported
  errors (about 18 s -> 0.1 s). Add a test that every key is applied.
- Validate the deployed QNX configs against the schema.
- Docs: describe the refuse-to-start behaviour and the table/schema
  consistency test. Fix the stale pdelay_interval_ms name in the detailed
  design and diagrams.
@github-project-automation github-project-automation Bot moved this to In Progress in TIM - Time FT Nov 16, 2026
@mattday-etas
mattday-etas marked this pull request as ready for review November 16, 2026 12:22
@mattday-etas mattday-etas changed the title Fix missing config validation Fix time_slave missing config validation Nov 16, 2026
@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

License Check Results

🚀 The license check job ran with the Bazel command:

bazel run //:license-check

Status: ⚠️ Needs Review

Click to expand output
[License Check Output]
Extracting Bazel installation...
Starting local Bazel server (8.8.2) and connecting to it...
INFO: Invocation ID: 03e516a9-5ab1-4e19-92a4-08277bcb93dd
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
Computing main repo mapping: 
WARNING: /home/runner/.bazel/external/score_baselibs+/score/json/BUILD:25:12: target '@@score_baselibs+//score/json:base_library' is deprecated: base_library no longer has any effect, vaJson is the only parser backend. Remove this flag from your build configuration; it will be deleted in a future release.
Loading: 
Loading: 3 packages loaded
WARNING: Target pattern parsing failed.
ERROR: Skipping '//:license-check': no such target '//:license-check': target 'license-check' not declared in package '' defined by /home/runner/work/time/time/BUILD
ERROR: no such target '//:license-check': target 'license-check' not declared in package '' defined by /home/runner/work/time/time/BUILD
INFO: Elapsed time: 17.590s
INFO: 0 processes.
ERROR: Build did NOT complete successfully
ERROR: Build failed. Not running target

@github-actions

github-actions Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Quality pack traceability report for this pull request:

Status: PASS (workflow run)

Traceability gate input: /home/runner/work/time/time/_build/metrics.json
------------------------------------------------------------------------
[comp_req]
  Requirements with source links: 40/58 (68.97%)
  Requirements with test links:   5/58 (8.62%)
  Requirements fully linked:      5/58 (8.62%)
  Tests linked to requirements:   8/474 (1.69%)
  Broken test references:         0
------------------------------------------------------------------------
Threshold check passed.

@github-actions

Copy link
Copy Markdown
Contributor

Documentation preview for this pull request is available at:
pr-332: https://eclipse-score.github.io/time/pr-332/

Drop default_value from the config schema table. The consistency test
now compares the schema's defaults with a default-constructed
TimeSlaveConfig, which replaces StructDefaultsMatchTable. The parser
test only checks that parsing {} leaves the struct defaults unchanged.

Rename config_limits.h to config_schema_table.h, since it holds keys,
types and ranges, not only limits.

@jorgecasal jorgecasal left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved with some minor suggestions.

In summary, the validation works as described and I found nothing blocking. However, I'd update the PR description, since main has no std::abort() or EXPECT_DEATH. I'd also like the comment on Finish() and the missing test for the refuse to start path either fixed here or possibly tracked in a follow up issue. The rest is up to you.

* - ``pdelay_req_interval_ms``
- int
- Interval between PDelayReq transmissions (ms); default: ``1000``
- Interval between PDelayReq transmissions (ms); range 10..60000; default: ``1000``

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the only row in the table that gives a range. The guide says the schema defines the ranges, so I'd leave it out here, otherwise we have one more place to keep in sync.

if (!std::filesystem::is_regular_file(path, ec))
{
score::mw::log::LogError(kTimeSlaveAppContext)
score::mw::log::LogWarn(kTimeSlaveAppContext)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed this went from LogError to LogWarn. It isn't mentioned in the description. Was that on purpose?

Comment on lines +80 to +84
template <const cs::IntProperty& Prop, typename T>
void Int(T& out)
{
static_assert(Prop.min >= std::numeric_limits<T>::min() && Prop.max <= std::numeric_limits<T>::max(),
"schema range of this property does not fit into the C++ field type");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It took me a while to see why Int is called as Int<cs::kDomainNumber>(out) when String and Bool take the property as a normal argument. Would it work to pass it the same way and keep the static_assert next to the table instead?

return;
}
const auto result = value->As<bool>();
if (value->As<score::json::Number>().has_value() || !result.has_value())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to read this twice and, think it's right, but a small helper like IsJsonBool(value) would make it obvious why the Number check comes first.

Comment on lines +184 to +199
void ParsePhcConfig(JsonObjectReader& root, std::vector<std::string>& errors, details::PhcConfig& cfg)
{
const JsonObject* phc_obj = root.NestedObject(cs::kPhcKey);
if (phc_obj == nullptr)
{
return;
}
JsonObjectReader reader{*phc_obj, cs::kPhcKey, cs::kPhcKeys, errors};
reader.Bool(cs::kPhcEnabled, cfg.enabled);
reader.String(cs::kPhcDevice, cfg.device);
reader.Int<cs::kPhcStepThresholdNs>(cfg.step_threshold_ns);
reader.Finish();
}

/// Parse the optional "qnx" nested object. If absent, @p qnx keeps defaults.
void ParseQnxConfig(const Object& obj, TimeSlaveConfig::QnxSettings& qnx)
void ParseQnxConfig(JsonObjectReader& root, std::vector<std::string>& errors, TimeSlaveConfig::QnxSettings& qnx)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The root reader already holds the errors vector, so passing errors as well looks redundant. Maybe the reader could hand out a child reader for the nested object?

Default Configuration (`GptpEngineOptions`)
-------------------------------------------

The following table lists all available options and their default values as defined in the source code. Currently, only ``iface_name`` can be changed without recompiling the application.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not new in this PR, but this sentence says only iface_name can be changed without recompiling, and that no longer fits the table below or the new Validation section. Could you fix it while you're editing this page?

Comment on lines +67 to +77
auto parsed = ParseConfig(config_path.string());
if (!parsed.ok())
{
for (const auto& error : parsed.errors)
{
score::mw::log::LogError(kTimeSlaveAppContext) << error;
}
score::mw::log::LogError(kTimeSlaveAppContext)
<< "Invalid configuration file " << config_path.string() << ", refusing to start";
return kInitFailure;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the main behaviour change of the PR, but I don't see a test that reaches it. My understanding is that time_slave.cpp is only built into the binary, so it's not trivial. Could we add one, or maybe open a follow up issue for it?

Comment on lines +285 to +290
TEST(ConfigParserTest, ReportsAllErrorsNotJustTheFirst)
{
const auto result = ParseConfig(WriteTempFile(
"multi_error.json", R"({"domain_number": 128, "sync_timeout_ms": 1, "phc": {"enabled": 1}, "typo": 0})"));
EXPECT_EQ(result.errors.size(), 4U);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only checks the number of errors. Could it also check that the four key names show up in the messages? Otherwise it would still pass with four wrong errors.

Comment on lines +356 to 363
/// Invalid JSON is an error (not defaults): the caller refuses to start on it.
TEST(ConfigParserTest, InvalidJsonIsReportedNotDefaulted)
{
const auto cfg = ParseConfig(WriteTempFile("invalid_config.json", "{not json"));
const auto result = ParseConfig(WriteTempFile("invalid_config.json", "{not json"));

EXPECT_EQ(cfg.engine_opts.iface_name, "emac0");
EXPECT_EQ(cfg.shm_path, "/gptp_shmem");
ASSERT_FALSE(result.ok());
EXPECT_NE(result.errors.front().find("Failed to parse"), std::string::npos);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct me if I'm wrong but, this looks like the same case as not_json in the list above (line 278). I think one of the two is enough.

target_compatible_with = ["@platforms//os:linux"],
)

# Deployed configurations must satisfy the schema too.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to see the deployed configs checked against the schema. A small parser test that loads the same two files would also show that ParseConfig itself accepts them.

This branch was previously deployed

1 inactive deployment
workflow-approval — fa704dcb Deployed Nov 18, 2026 by mattday-etas via qnx-build (x86_64-qnx) / approval #1348
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In Progress

Development

Successfully merging this pull request may close these issues.

Config values aren't validated against the schema

2 participants