Skip to content

Commit 73c95d1

Browse files
Merge pull request #38 from fastrevmd-lab/fix/rustnetconf-0.14-candidate-safety
release: rustez 0.14.0 — candidate-datastore safety (rustnetconf 0.14.0)
2 parents e1eee15 + b317394 commit 73c95d1

12 files changed

Lines changed: 305 additions & 13 deletions

File tree

‎CLAUDE.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,21 @@ Auth: set `RUSTEZ_VSRX_KEY` for key-based or `RUSTEZ_VSRX_PASS` for password aut
3535
- **quick-xml lifetime gotcha** — always bind `tag.local_name()` to a `let` before calling `.as_ref()`. The temporary must outlive the borrow.
3636
- **Error types** — `RustEzError` is the single error enum. Wraps `NetconfError` via `#[from]`. Use `thiserror` derive.
3737
- **Per-RPC timeouts** — wrap every `client.rpc()` / `client.commit()` call in `tokio::time::timeout`. Default 30s.
38-
- **Config loading** — uses `client.load_configuration(action, format, config)` from rustnetconf 0.6. `build_load_xml()` retained only for `rollback()` and `load_with_warnings()`.
38+
- **Config loading** — uses `client.load_configuration(action, format, config)` from rustnetconf 0.6. `build_load_xml()` is retained for `load_with_warnings()` only — that is the one candidate-modifying call still on the raw `rpc_with_warnings()` escape hatch, because rustnetconf has no `rpc_candidate_change_with_warnings`. `rollback()` uses the typed `client.rollback_configuration()`.
3939
- **ConfigPayload::Set** — maps to `LoadAction::Set, LoadFormat::Text`.
4040
- **Namespace prefix** — `build_load_xml()` uses `nc:` prefix on XML elements to match rustnetconf 0.7.1's `<nc:rpc>` envelope. Required for Junos 24.4 compatibility.
4141
- **Cluster auto-open** — `ConfigManager::load()` auto-calls `open_configuration(Private)` on clustered devices. `unlock()` auto-closes it. State tracked on `Device.config_db_open`.
42+
- **Candidate-dirty tracking** — rustnetconf 0.14 only sends `<discard-changes/>` on close when *this* session dirtied the shared
43+
candidate. Typed ops (`load_configuration`, `rollback_configuration`, `edit_config`) mark it automatically; the raw `rpc()` /
44+
`rpc_with_warnings()` path does not. **Prefer `RpcExecutor::call_xml_candidate_change()`** (Python:
45+
`Device.rpc.raw_xml_candidate_change()`), which routes through `client.rpc_candidate_change()` and validates → preflights →
46+
marks → sends atomically. Surfaced to callers as `Device::touched_candidate()`.
47+
- **A false dirty mark is worse than a missing one** — a missing mark leaves a dirty candidate that blocks the next lock; a false
48+
mark makes `close()` discard *another operator's* uncommitted work, which is the bug this tracking exists to prevent. So if you
49+
must hand-mark (only `load_with_warnings()` does, because there is no `rpc_candidate_change_with_warnings`), **validate the
50+
fragment with `rustnetconf::rpc::validate_xml_fragment()` first, and validate before opening the config database** — the raw
51+
`rpc*` calls reject a malformed fragment locally without sending, and `ConfigPayload::Xml` passes caller XML through unescaped.
52+
Mark after validation but before the send, so a timeout or partial apply still counts.
4253
- **Warnings** — `RpcExecutor::call_with_warnings()` / `call_xml_with_warnings()` return `(String, Vec<RpcErrorInfo>)`. `ConfigManager::load_with_warnings()` does the same for config loads.
4354

4455
## Architecture

‎rustez-cli/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ publish = false
1111

1212
[dependencies]
1313
rustez = { path = "../rustez" }
14-
rustnetconf = "0.13.1"
14+
rustnetconf = "0.14.0"
1515
tokio = { version = "1", features = ["full"] }
1616
clap = { version = "4", features = ["derive"] }
1717
serde = { version = "1", features = ["derive"] }

‎rustez-py/Cargo.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "rustez-py"
3-
version = "0.13.1"
3+
version = "0.14.0"
44
edition = "2021"
55
authors = ["fastrevmd-lab"]
66
description = "Python bindings for rustEZ — pip install rustez"
@@ -15,6 +15,6 @@ crate-type = ["cdylib"]
1515

1616
[dependencies]
1717
rustez = { path = "../rustez" }
18-
rustnetconf = "0.13.1"
18+
rustnetconf = "0.14.0"
1919
pyo3 = { version = "0.29", features = ["extension-module"] }
2020
tokio = { version = "1", features = ["full"] }

‎rustez-py/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ build-backend = "maturin"
44

55
[project]
66
name = "rustez"
7-
version = "0.13.1"
7+
version = "0.14.0"
88
description = "Python bindings for rustEZ — Junos device automation built on Rust"
99
requires-python = ">=3.9"
1010
license = "MIT"

‎rustez-py/python/rustez/__init__.py‎

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,12 @@ def _do_get_config(self, kwargs: dict):
153153
def raw_xml(self, xml: str):
154154
"""Send a raw XML RPC and return the parsed lxml response element.
155155
156-
Escape hatch for RPCs that aren't expressible via attribute access
157-
(e.g. ``<load-configuration action="replace">``). Errors go through
158-
``classify_error`` so callers receive typed exceptions
156+
Escape hatch for RPCs that aren't expressible via attribute access.
157+
For RPCs that modify the candidate datastore (e.g.
158+
``<load-configuration>``, ``<edit-config>`` on candidate), use
159+
``raw_xml_candidate_change()`` instead to ensure cleanup on close.
160+
161+
Errors go through ``classify_error`` so callers receive typed exceptions
159162
(``ConnectError``, ``RpcError``, ``ConfigLoadError``, etc.) instead
160163
of bare ``RuntimeError``.
161164
@@ -168,13 +171,47 @@ def raw_xml(self, xml: str):
168171
Raises:
169172
RpcError / ConfigLoadError / ConnectError: Classified from the
170173
native error string.
174+
175+
Example (non-candidate RPC):
176+
>>> dev.rpc.raw_xml('<get-chassis-inventory/>')
171177
"""
172178
try:
173179
xml_str = self._native.rpc_xml(xml)
174180
except RuntimeError as exc:
175181
raise classify_error(exc) from exc
176182
return _parse_xml(xml_str)
177183

184+
def raw_xml_candidate_change(self, xml: str):
185+
"""Send a raw XML RPC that modifies the candidate datastore.
186+
187+
Use this for ``<load-configuration>``, ``<edit-config>`` on candidate,
188+
and similar operations. This marks the candidate dirty so that
189+
``close()`` properly cleans up. For read-only RPCs, use ``raw_xml()``
190+
instead.
191+
192+
Errors go through ``classify_error`` so callers receive typed exceptions
193+
(``ConnectError``, ``RpcError``, ``ConfigLoadError``, etc.) instead
194+
of bare ``RuntimeError``.
195+
196+
Args:
197+
xml: Raw XML RPC payload (inner element — no ``<rpc>`` envelope).
198+
199+
Returns:
200+
lxml.etree.Element parsed from the response.
201+
202+
Raises:
203+
RpcError / ConfigLoadError / ConnectError: Classified from the
204+
native error string.
205+
206+
Example:
207+
>>> dev.rpc.raw_xml_candidate_change('<load-configuration action="replace">...</load-configuration>')
208+
"""
209+
try:
210+
xml_str = self._native.rpc_xml_candidate_change(xml)
211+
except RuntimeError as exc:
212+
raise classify_error(exc) from exc
213+
return _parse_xml(xml_str)
214+
178215
def _do_named_rpc(self, name: str, kwargs: dict):
179216
"""Execute a named RPC with keyword arguments.
180217
@@ -373,6 +410,21 @@ def is_cluster(self) -> bool:
373410
except RuntimeError:
374411
return False
375412

413+
def touched_candidate(self) -> bool:
414+
"""Whether this session may have modified the shared candidate datastore.
415+
416+
Returns True when the session has performed operations that mark the
417+
candidate dirty and have not yet been followed by a successful commit
418+
or discard. Useful for deciding whether a pooled session is safe to reuse.
419+
420+
Returns:
421+
bool: True if the candidate may be dirty, False otherwise.
422+
"""
423+
try:
424+
return self._native.touched_candidate()
425+
except RuntimeError:
426+
return False
427+
376428
def cli(self, command: str, warning: bool = True) -> str:
377429
"""Execute a CLI command and return text output.
378430

‎rustez-py/src/lib.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,16 @@ impl PyDevice {
181181
Ok(guard.as_ref().is_some_and(|dev| dev.is_cluster()))
182182
}
183183

184+
/// Whether this session may have modified the shared candidate datastore.
185+
///
186+
/// Returns True when the session has performed operations that mark the
187+
/// candidate dirty and have not yet been followed by a successful commit
188+
/// or discard. A closed device returns False.
189+
fn touched_candidate(&self) -> PyResult<bool> {
190+
let guard = lock_mutex(&self.device)?;
191+
Ok(guard.as_ref().is_some_and(|dev| dev.touched_candidate()))
192+
}
193+
184194
/// Return facts as a Python dict.
185195
fn facts(&self, py: Python<'_>) -> PyResult<Vec<(String, String)>> {
186196
py.detach(|| {
@@ -267,6 +277,21 @@ impl PyDevice {
267277
})
268278
}
269279

280+
/// Send raw XML RPC that modifies the candidate datastore. Returns raw XML string.
281+
fn rpc_xml_candidate_change(&self, py: Python<'_>, xml: &str) -> PyResult<String> {
282+
let xml = xml.to_string();
283+
py.detach(|| {
284+
let mut guard = lock_mutex(&self.device)?;
285+
let dev = guard
286+
.as_mut()
287+
.ok_or_else(|| PyRuntimeError::new_err("not connected"))?;
288+
let mut rpc = dev.rpc().map_err(to_py_err)?;
289+
self.runtime
290+
.block_on(rpc.call_xml_candidate_change(&xml))
291+
.map_err(to_py_err)
292+
})
293+
}
294+
270295
/// Send raw XML RPC and return any warnings alongside the response.
271296
///
272297
/// Returns `(response_xml, [(severity, message), ...])`.
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
"""Tests for candidate-datastore tracking on the public Python surface.
2+
3+
rustnetconf 0.14 only sends ``<discard-changes/>`` on close when the session
4+
actually dirtied the shared candidate. Two pieces of that contract are exposed
5+
to Python, and both are easy to break by adding a method to the native
6+
extension type while forgetting the hand-written ``Device`` / ``_RpcProxy``
7+
wrappers that ``from rustez import Device`` actually returns.
8+
9+
That is not hypothetical: ``Device.touched_candidate()`` shipped in exactly
10+
that broken state (present on ``PyDevice``, missing on ``Device``) and raised
11+
``AttributeError`` for every caller. These are surface tests — they assert the
12+
public wrappers forward, not that the underlying tracking is correct, which
13+
needs a device and is covered by the gated integration tests.
14+
"""
15+
16+
import pytest
17+
18+
from rustez import Device
19+
from rustez._rustez_native import PyDevice
20+
21+
22+
def test_device_wrapper_exposes_touched_candidate():
23+
"""The PUBLIC Device wrapper must expose touched_candidate, not just PyDevice.
24+
25+
`from rustez import Device` returns the hand-written wrapper, which forwards
26+
each method explicitly and has no __getattr__ delegation.
27+
"""
28+
assert hasattr(Device, "touched_candidate")
29+
assert callable(Device.touched_candidate)
30+
31+
32+
def test_native_device_exposes_touched_candidate():
33+
"""The native extension type backs the wrapper above."""
34+
assert hasattr(PyDevice, "touched_candidate")
35+
assert callable(PyDevice.touched_candidate)
36+
37+
38+
def test_native_device_exposes_rpc_xml_candidate_change():
39+
"""Candidate-modifying raw RPCs need a tracked path on the native type."""
40+
assert hasattr(PyDevice, "rpc_xml_candidate_change")
41+
assert callable(PyDevice.rpc_xml_candidate_change)
42+
43+
44+
def test_rpc_proxy_exposes_raw_xml_candidate_change():
45+
"""The rpc proxy must offer the tracked variant alongside raw_xml.
46+
47+
raw_xml() does not mark the candidate; sending <load-configuration> through
48+
it leaves the shared candidate dirty and blocks the next session's lock.
49+
"""
50+
from rustez import _RpcProxy
51+
52+
assert hasattr(_RpcProxy, "raw_xml_candidate_change")
53+
assert callable(_RpcProxy.raw_xml_candidate_change)
54+
# The untracked escape hatch must still exist — this is additive, not a swap.
55+
assert hasattr(_RpcProxy, "raw_xml")

‎rustez/CHANGELOG.md‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,84 @@ All notable changes to the `rustez` crate are documented in this file.
55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
66
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
77

8+
## [0.14.0] — 2026-08-19
9+
10+
### Fixed
11+
12+
- **Closing a session no longer discards another operator's uncommitted work**
13+
(#36). Junos exposes a **shared** candidate datastore, and `Device::close()`
14+
previously caused an unconditional `<discard-changes/>`. A session that merely
15+
read, or whose `<lock>` was refused with `configuration database modified`,
16+
destroyed exactly the work that caused the refusal — silently, with no error
17+
and no log. The upstream fix (rustnetconf #55 / 0.14.0) tracks whether *this*
18+
session dirtied the candidate and discards only then, so the safety property
19+
is kept without the collateral damage.
20+
21+
- **`load_with_warnings()` now marks the candidate dirty.** It is the one
22+
candidate-modifying call still on the raw `rpc_with_warnings()` escape hatch,
23+
because rustnetconf has no `rpc_candidate_change_with_warnings` variant. Under
24+
0.14.0's conditional discard it would otherwise have left a dirty candidate
25+
behind at close, blocking the next session's lock. The mark is issued
26+
**before** the send, so a timeout or partially-applied load still counts —
27+
but **after** the payload is validated locally, because `rpc_with_warnings()`
28+
rejects a malformed fragment without sending anything. Marking first would
29+
leave a false mark on a load that never happened, and `close()` acting on it
30+
would discard a third party's work — the very bug above, reintroduced.
31+
`ConfigPayload::Xml` passes caller XML through unescaped, so that path was
32+
reachable. Validation now runs before the configuration database is opened,
33+
so an invalid payload fails with no side effects at all.
34+
35+
- **Candidate-modifying RPCs sent through the raw escape hatch are tracked
36+
again.** `RpcExecutor::call_xml()` and `call_xml_with_warnings()` do not mark
37+
the candidate, and before 0.14.0 the unconditional discard covered them
38+
anyway. It no longer does, which silently regressed a documented path — the
39+
Python `Device.rpc.raw_xml()` docstring gave `<load-configuration
40+
action="replace">` as its worked example. See *Added* for the replacement.
41+
42+
### Added
43+
44+
- **`RpcExecutor::call_xml_candidate_change()`**, exposed to Python as
45+
**`Device.rpc.raw_xml_candidate_change()`** — the supported way to send a
46+
candidate-modifying RPC over the raw path. It routes through rustnetconf's
47+
`rpc_candidate_change()`, which validates, runs the send preflight, marks, and
48+
only then writes, so a locally rejected fragment cannot leave a false mark.
49+
`call_xml()` / `call_xml_with_warnings()` / `raw_xml()` keep their existing
50+
behaviour and now say plainly in their docs that they do **not** track the
51+
candidate. This is a deliberate second method rather than a flag on the
52+
existing one, mirroring upstream, because a flag is too easy to forget.
53+
54+
- **`Device::touched_candidate() -> bool`** (#36) — whether this session has a
55+
candidate-modifying operation outstanding against the shared datastore. Lets a
56+
connection-pooling layer decide whether a session is safe to return to the
57+
pool or must be closed so the discard happens. A closed device returns
58+
`false`. Exposed to Python as `Device.touched_candidate()` — on the public
59+
`rustez.Device` wrapper, not only the native extension type.
60+
61+
### Changed
62+
63+
- Bumped `rustnetconf` to `0.14.0`, which also picks up two fixes from the
64+
intervening patch releases:
65+
- **0.13.2** — Junos chassis clusters return commit-check/`validate` replies
66+
whose `<routing-engine>` elements are opened but never closed, which broke
67+
the strict XML parser. This affected `ConfigManager::commit_check()` on
68+
clusters directly.
69+
- **0.13.3** — hardened RPC reply parsing for malformed and partial replies.
70+
- No `Cargo.lock` is committed for this library, so the SSH transport resolves
71+
to the newest compatible `russh` 0.62.x at build time — which now includes
72+
the `Channel::data()` backpressure fix that rustnetconf 0.13.3 called out.
73+
74+
### Known limitations
75+
76+
- **`commit_with_comment()` leaves a stale candidate-dirty mark.** It sends
77+
`<commit-configuration><log>` through the raw `rpc()` path, and a successful
78+
commit normally *clears* the flag — but rustnetconf exposes neither a typed
79+
commit-with-comment nor a public flag-clearing method, so the clear cannot
80+
happen. The session therefore still discards at close. This is **not a
81+
regression** — 0.13.1 discarded unconditionally regardless — it is an
82+
improvement this one method does not yet get. The residual risk is narrow: a
83+
third party would have to dirty the shared candidate in the window between
84+
our commit and our close.
85+
886
## [0.13.1] — 2026-07-22
987

1088
### Changed
@@ -111,6 +189,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
111189
was `AcceptAll`. Since `rustnetconf 0.11` the default has been `RejectAll`
112190
(fail-closed); the docs now reflect this.
113191

192+
[0.14.0]: https://github.com/fastrevmd-lab/rustez/compare/v0.13.1...v0.14.0
114193
[0.13.1]: https://github.com/fastrevmd-lab/rustez/compare/v0.13.0...v0.13.1
115194
[0.13.0]: https://github.com/fastrevmd-lab/rustez/compare/v0.12.1...v0.13.0
116195
[0.12.1]: https://github.com/fastrevmd-lab/rustez/compare/v0.12.0...v0.12.1

‎rustez/Cargo.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "rustez"
3-
version = "0.13.1"
3+
version = "0.14.0"
44
edition = "2021"
55
authors = ["fastrevmd-lab"]
66
description = "A Rust replacement for Juniper PyEZ — async-first Junos automation built on rustnetconf"
@@ -11,7 +11,7 @@ categories = ["network-programming"]
1111
rust-version = "1.79"
1212

1313
[dependencies]
14-
rustnetconf = "0.13.1"
14+
rustnetconf = "0.14.0"
1515
tokio = { version = "1", features = ["full"] }
1616
quick-xml = "0.41"
1717
thiserror = "2"

‎rustez/src/config.rs‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::time::Duration;
44

55
use quick_xml::escape::escape;
66
use rustnetconf::rpc::RpcErrorInfo;
7-
use rustnetconf::{Client, Datastore, LoadAction, LoadFormat, OpenConfigurationMode};
7+
use rustnetconf::{Client, Datastore, LoadAction, LoadFormat, NetconfError, OpenConfigurationMode};
88

99
/// XML namespace prefix used by rustnetconf for NETCONF RPCs.
1010
const NC: &str = "nc:";
@@ -124,13 +124,25 @@ impl<'a> ConfigManager<'a> {
124124
/// Warnings are non-fatal messages (severity="warning") that the device
125125
/// returns alongside a successful load. See [`load()`](Self::load) for
126126
/// the auto-open and error-cleanup behavior.
127+
///
128+
/// This method marks the candidate dirty so that `close_session()` knows
129+
/// a discard may be needed.
127130
pub async fn load_with_warnings(
128131
&mut self,
129132
payload: ConfigPayload,
130133
) -> Result<(String, Vec<RpcErrorInfo>), RustEzError> {
134+
// Build and validate the XML BEFORE opening or marking. rpc_with_warnings
135+
// internally calls validate_xml_fragment and returns early if malformed,
136+
// without sending anything. Validation must precede the mark because a
137+
// false mark causes close() to discard a third party's work. This does not
138+
// replicate upstream's keepalive/ensure_established preflight — only
139+
// rpc_candidate_change does that, and it has no warnings variant.
140+
let xml = build_load_xml(&payload);
141+
rustnetconf::rpc::validate_xml_fragment(&xml).map_err(NetconfError::from)?;
142+
131143
let opened_here = self.auto_open_if_needed().await?;
132144

133-
let xml = build_load_xml(&payload);
145+
self.client.mark_candidate_dirty();
134146
let timeout = self.timeout;
135147
let result = timed(timeout, self.client.rpc_with_warnings(&xml)).await;
136148
if result.is_err() {
@@ -194,6 +206,10 @@ impl<'a> ConfigManager<'a> {
194206
pub async fn commit_with_comment(&mut self, comment: &str) -> Result<(), RustEzError> {
195207
let timeout = self.timeout;
196208
let xml = build_commit_with_comment_xml(comment);
209+
// Known limitation: the raw rpc() path cannot clear the candidate-dirty
210+
// flag because rustnetconf exposes no typed commit-with-comment and no
211+
// public flag-clearing method. A session using this method will still
212+
// send a (harmless-for-its-own-changes) <discard-changes/> at close.
197213
timed(timeout, self.client.rpc(&xml)).await.map(|_| ())
198214
}
199215

0 commit comments

Comments
 (0)