public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Joaquin Varela <joaquinvarela@neatech.ar>
To: pve-devel@lists.proxmox.com
Subject: [PATCH storage v5 09/13] test: zfsnvme: add an in-memory nvmet target
Date: Thu, 26 Nov 2026 12:09:50 -0300	[thread overview]
Message-ID: <20261126150956.310593-10-joaquinvarela@neatech.ar> (raw)
In-Reply-To: <20261126150956.310593-1-joaquinvarela@neatech.ar>

Add zfsnvme_target_test.pm with FakeTarget, an in-memory target that
runs exactly the commands the plugin sends and records anything else as
a protocol violation, and check it against fixture reads of a real
target (Linux 6.8, ZFS 2.2, documentation addresses).

Signed-off-by: Joaquin Varela <joaquinvarela@neatech.ar>
---
 src/test/run_plugin_tests.pl                  |    1 +
 .../zfsnvme_fixtures/configfs_snapshot.txt    |   38 +
 src/test/zfsnvme_fixtures/zfs_inventory.txt   |   15 +
 src/test/zfsnvme_target_test.pm               | 1578 +++++++++++++++++
 4 files changed, 1632 insertions(+)
 create mode 100644 src/test/zfsnvme_fixtures/configfs_snapshot.txt
 create mode 100644 src/test/zfsnvme_fixtures/zfs_inventory.txt
 create mode 100644 src/test/zfsnvme_target_test.pm

diff --git a/src/test/run_plugin_tests.pl b/src/test/run_plugin_tests.pl
index 19465c25..99ea2f46 100755
--- a/src/test/run_plugin_tests.pl
+++ b/src/test/run_plugin_tests.pl
@@ -26,6 +26,7 @@ my $res = $harness->runtests(
     "plugin_load_test.pm",
     "plugin_properties_test.pm",
     "zfsnvme_test.pm",
+    "zfsnvme_target_test.pm",
 );
 
 exit -1 if !$res || $res->{failed} || $res->{parse_errors};
diff --git a/src/test/zfsnvme_fixtures/configfs_snapshot.txt b/src/test/zfsnvme_fixtures/configfs_snapshot.txt
new file mode 100644
index 00000000..1b7672a0
--- /dev/null
+++ b/src/test/zfsnvme_fixtures/configfs_snapshot.txt
@@ -0,0 +1,38 @@
+D /sys/kernel/config/nvmet
+D /sys/kernel/config/nvmet/hosts
+D /sys/kernel/config/nvmet/hosts/nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a
+D /sys/kernel/config/nvmet/hosts/nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b
+D /sys/kernel/config/nvmet/ports
+D /sys/kernel/config/nvmet/ports/2
+D /sys/kernel/config/nvmet/ports/2/subsystems
+D /sys/kernel/config/nvmet/ports/1
+D /sys/kernel/config/nvmet/ports/1/subsystems
+D /sys/kernel/config/nvmet/subsystems
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6
+D /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5
+L /sys/kernel/config/nvmet/ports/2/subsystems/nqn.2026-01.com.example:zfsnvme
+L /sys/kernel/config/nvmet/ports/1/subsystems/nqn.2026-01.com.example:zfsnvme
+L /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts/nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a
+L /sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/allowed_hosts/nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b
+/sys/kernel/config/nvmet/ports/2/addr_trtype:tcp
+/sys/kernel/config/nvmet/ports/2/addr_trsvcid:4420
+/sys/kernel/config/nvmet/ports/2/addr_traddr:192.0.2.22
+/sys/kernel/config/nvmet/ports/2/addr_adrfam:ipv4
+/sys/kernel/config/nvmet/ports/1/addr_trtype:tcp
+/sys/kernel/config/nvmet/ports/1/addr_trsvcid:4420
+/sys/kernel/config/nvmet/ports/1/addr_traddr:192.0.2.21
+/sys/kernel/config/nvmet/ports/1/addr_adrfam:ipv4
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/buffered_io:0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/enable:1
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/device_uuid:0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/6/device_path:/dev/zvol/tank/vm-100-cloudinit
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/buffered_io:0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/enable:1
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/device_uuid:0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/namespaces/5/device_path:/dev/zvol/tank/vm-100-disk-0
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_model:Proxmox ZFS NVMe
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_serial:PVEZFS51b2c3c90ea254
+/sys/kernel/config/nvmet/subsystems/nqn.2026-01.com.example:zfsnvme/attr_allow_any_host:0
diff --git a/src/test/zfsnvme_fixtures/zfs_inventory.txt b/src/test/zfsnvme_fixtures/zfs_inventory.txt
new file mode 100644
index 00000000..69ba9238
--- /dev/null
+++ b/src/test/zfsnvme_fixtures/zfs_inventory.txt
@@ -0,0 +1,15 @@
+tank	type	filesystem	-
+tank	proxmox:nvme-subsys	-	-
+tank	proxmox:nvme-nsid	-	-
+tank	proxmox:nvme-uuid	-	-
+tank	proxmox:nvme-last-nsid	-	-
+tank/vm-100-cloudinit	type	volume	-
+tank/vm-100-cloudinit	proxmox:nvme-subsys	nqn.2026-01.com.example:zfsnvme	local
+tank/vm-100-cloudinit	proxmox:nvme-nsid	6	local
+tank/vm-100-cloudinit	proxmox:nvme-uuid	0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d	local
+tank/vm-100-cloudinit	proxmox:nvme-last-nsid	-	-
+tank/vm-100-disk-0	type	volume	-
+tank/vm-100-disk-0	proxmox:nvme-subsys	nqn.2026-01.com.example:zfsnvme	local
+tank/vm-100-disk-0	proxmox:nvme-nsid	5	local
+tank/vm-100-disk-0	proxmox:nvme-uuid	0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c	local
+tank/vm-100-disk-0	proxmox:nvme-last-nsid	-	-
diff --git a/src/test/zfsnvme_target_test.pm b/src/test/zfsnvme_target_test.pm
new file mode 100644
index 00000000..22b9585b
--- /dev/null
+++ b/src/test/zfsnvme_target_test.pm
@@ -0,0 +1,1578 @@
+# Target side of the zfsnvme plugin: the parsers and planners on the fixture reads, the command
+# renderer and every target flow against an in-memory NVMe target (FakeTarget) that interprets
+# exactly the commands the plugin sends. Nothing here opens a connection or touches local devices.
+
+use v5.36;
+
+use lib qw(..);
+
+use Compress::Zlib qw(crc32);
+use Digest::SHA qw(sha256_hex);
+use File::Temp qw(tempdir);
+use FindBin;
+use IPC::Open3;
+use MIME::Base64 qw(encode_base64);
+use POSIX ();
+use Storable qw(dclone freeze);
+use Symbol qw(gensym);
+use Test::MockModule;
+use Test::More;
+
+use PVE::Cluster;
+use PVE::NVMeOF;
+use PVE::Storage;
+use PVE::Storage::ZFSNVMePlugin;
+
+my $PLUGIN = 'PVE::Storage::ZFSNVMePlugin';
+my $ROOT = '/sys/kernel/config/nvmet';
+my $MARKER = 'ZFSNVME-CONFIGFS';
+my $MODEL = 'Proxmox ZFS NVMe';
+my $FIXTURES = "$FindBin::Bin/zfsnvme_fixtures";
+my $UUID_RE = qr/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/i;
+my $EMPTY_KEY_SHA = sha256_hex("\n");
+
+# The fixtures are the ZFS inventory and the configfs read of a target (Linux 6.8 nvmet, ZFS 2.2)
+# that serves one subsystem with two namespaces to two cluster nodes, as the plugin reads them.
+my $FIXTURE_NQN = 'nqn.2026-01.com.example:zfsnvme';
+my @FIXTURE_HOSTS = (
+    'nqn.2014-08.org.nvmexpress:uuid:0a0a0a0a-0a0a-4a0a-8a0a-0a0a0a0a0a0a',
+    'nqn.2014-08.org.nvmexpress:uuid:0b0b0b0b-0b0b-4b0b-8b0b-0b0b0b0b0b0b',
+);
+my $FIXTURE_UUID5 = '0c0c0c0c-0c0c-4c0c-8c0c-0c0c0c0c0c0c';
+my $FIXTURE_UUID6 = '0d0d0d0d-0d0d-4d0d-8d0d-0d0d0d0d0d0d';
+
+my $NQN = 'nqn.2026-01.com.example:zfsnvme-test';
+my $FOREIGN_NQN = 'nqn.2026-01.com.example:foreign';
+my @HOSTS =
+    map { sprintf('nqn.2014-08.org.nvmexpress:uuid:00000000-0000-4000-8000-%012d', $_) } 1, 2;
+
+sub portal($family, $address, $port) {
+    return { family => $family, address => $address, port => $port };
+}
+my $PORTALS = [portal('ipv4', '192.0.2.21', 4420), portal('ipv4', '192.0.2.22', 4420)];
+my %U = map {
+    my $d = $_;
+    ($d => join('-', $d x 8, $d x 4, '4' . $d x 3, '8' . $d x 3, $d x 12))
+} 1 .. 9;
+
+sub make_key($hash, $length, $seed = 1) {
+    my $raw = join('', map { chr(($_ * 131 + $seed * 17) % 256) } 1 .. $length);
+    return "DHHC-1:$hash:" . encode_base64($raw . pack('V', crc32($raw)), '') . ':';
+}
+my $KEY = make_key('00', 32);
+my $KEY_B = make_key('00', 32, 2);
+my $KEY_SHA = sha256_hex("$KEY\n");
+
+sub scfg(%override) {
+    return {
+        type => 'zfsnvme',
+        server => '192.0.2.10',
+        pool => 'tank',
+        subsysnqn => $NQN,
+        blocksize => '16k',
+        sparse => 1,
+        'nvme-portals' => '192.0.2.21,192.0.2.22',
+        'nvme-host-ifaces' => 'ens19,ens20',
+        'nvme-host-nqns' => join(',', @HOSTS),
+        %override,
+    };
+}
+
+sub slurp($path) {
+    open(my $fh, '<', $path) or die "cannot open '$path': $!\n";
+    local $/;
+    return scalar(<$fh>);
+}
+
+# Calls a plugin package sub by name, so a mocked sub is the one called.
+sub nv($name, @args) {
+    my $code = $PLUGIN->can($name) // die "plugin has no sub '$name'\n";
+    return $code->(@args);
+}
+
+sub same($x, $y) {
+    local $Storable::canonical = 1;
+    return freeze([$x]) eq freeze([$y]);
+}
+
+# Mocks: the only way to the target is _nvmet_run, and it reaches $FAKE. The pmxcfs lock, quorum,
+# clock, waits, UUID source, local files and local devices are mocked, waits advance $NOW.
+
+our $FAKE;
+our $NOW = 1_000_000;
+our $SLEPT = 0;
+our $QUORATE = 1;
+our $LOCK_HOOK;
+our (%LOCK_HELD, @LOCKS, @NESTED_LOCKS, @QUORUM, @WARNINGS, @SYSFS_WRITES, %FILES, %CONFIG);
+our (%CORPUS, @VIOLATIONS, @WRITES, %BLOCK, @UUIDS);
+
+my $uuid_seq = 0;
+
+sub lock_id($scfg) {
+    return 'zfsnvme-' . ($scfg->{server} =~ s/[^A-Za-z0-9.-]/_/gr);
+}
+
+sub lock_held($scfg) {
+    return (($LOCK_HELD{ lock_id($scfg) } // 0) == $$) ? 1 : 0;
+}
+
+# by the vocabulary of the fake target, independently of the plugin
+sub step_is($step, @prefix) {
+    return
+        ref($step) eq 'ARRAY'
+        && $step->@* >= @prefix
+        && join("\0", $step->@[0 .. $#prefix]) eq join("\0", @prefix);
+}
+
+sub write_to($step, $suffix, $value = undef) {
+    return
+        ref($step) eq 'HASH'
+        && exists($step->{write})
+        && $step->{write} =~ m{\Q$suffix\E\z}
+        && (!defined($value) || $step->{value} eq $value);
+}
+
+sub mutating_step($step) {
+    return 1 if ref($step) ne 'ARRAY';
+    my ($command, $subcommand) = $step->@*;
+    return 0 if grep { $command eq $_ } qw(test grep cat printf env);
+    return 0 if $command eq 'zfs' && ($subcommand eq 'get' || $subcommand eq 'list');
+    return 1;
+}
+
+# Whether steps change the target, not counting the module load of a locked read.
+sub changing($steps) {
+    return scalar(grep { mutating_step($_) && !step_is($_, 'modprobe') } $steps->@*);
+}
+
+my $plugin_mock = Test::MockModule->new($PLUGIN);
+my $cluster_mock = Test::MockModule->new('PVE::Cluster');
+my $storage_mock = Test::MockModule->new('PVE::Storage');
+my $sysfs_mock = Test::MockModule->new('PVE::SysFSTools');
+my $tools_mock = Test::MockModule->new('PVE::Tools');
+
+$plugin_mock->redefine(
+    _nvmet_run => sub($scfg, $steps, %opts) {
+        die "test error: no fake target\n" if !$FAKE;
+        my $rendered = nv('_nvmet_render', $steps);
+        $CORPUS{$rendered} //= $opts{op} // '';
+        return $FAKE->run($scfg, $steps, $rendered, %opts);
+    },
+);
+# The target is the only place that runs commands, and only through _nvmet_run.
+# A command is also a violation, in case the caller handles the error.
+my $no_command = sub($cmd, %opts) {
+    my $what = 'unexpected command ' . (ref($cmd) ? $cmd->[0] : $cmd);
+    push @VIOLATIONS, $what;
+    die "test error: $what\n";
+};
+$plugin_mock->redefine(run_command => $no_command);
+$tools_mock->redefine(run_command => $no_command);
+$plugin_mock->redefine(_now => sub () { return $NOW });
+$plugin_mock->redefine(
+    _sleep => sub($seconds) {
+        $NOW += $seconds;
+        $SLEPT += $seconds;
+        return;
+    },
+);
+$plugin_mock->redefine(_block_device => sub($path) { return $BLOCK{$path} });
+$plugin_mock->redefine(log_warn => sub($message) { push @WARNINGS, $message; return });
+my $sysfs_write = sub($path, $data, $allow_existing = undef) {
+    push @SYSFS_WRITES, [$path, $data];
+    return 1;
+};
+$sysfs_mock->redefine(file_write => $sysfs_write);
+# UUIDs come from @UUIDS first, then from a sequence.
+$plugin_mock->redefine(
+    file_read_firstline => sub($path) {
+        if ($path eq '/proc/sys/kernel/random/uuid') {
+            return shift(@UUIDS) if @UUIDS;
+            $uuid_seq++;
+            return sprintf('%08x-7e57-4000-8000-%012x', $uuid_seq, $uuid_seq);
+        }
+        return $FILES{$path};
+    },
+);
+$plugin_mock->redefine(
+    file_set_contents => sub($path, $data, $perm = undef, @rest) {
+        push @WRITES, { path => $path, data => $data, perm => $perm };
+        return;
+    },
+);
+$plugin_mock->redefine(make_path => sub(@args) { push @WRITES, { make_path => [@args] }; return });
+
+$cluster_mock->redefine(
+    check_cfs_quorum => sub($noerr = undef) {
+        push @QUORUM, $noerr;
+        die "cluster not ready - no quorum?\n" if !$QUORATE && !$noerr;
+        return $QUORATE;
+    },
+);
+# Keeps the cfs_lock contract: the result of the code with $@ cleared, or undef with $@ set. pmxcfs
+# locks are not re-entrant, so a second request for a held lock times out like a mkdir on
+# /etc/pve/priv/lock would.
+$cluster_mock->redefine(
+    cfs_lock_domain => sub($name, $timeout, $code, @param) {
+        push @LOCKS, { name => $name, timeout => $timeout, pid => $$, now => $NOW };
+        if ($LOCK_HELD{$name}) {
+            push @NESTED_LOCKS, $name;
+            $@ = "cfs-lock 'domain-$name' error: got lock request timeout\n";
+            return undef;
+        }
+        if (my $hook = $LOCK_HOOK) {
+            local $LOCK_HOOK;
+            $hook->($name);
+        }
+        local $LOCK_HELD{$name} = $$;
+        my $res = eval { $code->(@param) };
+        my $err = $@;
+        if ($err) {
+            $@ = $err;
+            return undef;
+        }
+        $@ = undef;
+        return $res;
+    },
+);
+$storage_mock->redefine(config => sub () { return { ids => {%CONFIG} } });
+
+# FakeTarget: ZFS datasets and an nvmet configfs tree with the kernel rules the plugin depends on.
+# It accepts only the command vocabulary of the plugin, anything else is a protocol violation.
+
+package FakeTarget {
+    use Digest::SHA qw(sha256_hex);
+    use Storable qw(dclone);
+
+    my $RR = quotemeta($ROOT);
+
+    # The option fail is a list of [$match, $error, $times]. The steps that match (an argv prefix, a
+    # hash with write and value, or a sub of the step) fail $times times with $error.
+    sub new($class, %opts) {
+        my $pools = delete($opts{pools}) // ['tank'];
+        if (my $fail = delete($opts{fail})) {
+            my ($match, $error, $times) = $fail->@*;
+            my $matches =
+                ref($match) eq 'CODE' ? $match
+                : ref($match) eq 'HASH'
+                ? sub($step) { main::write_to($step, $match->{write}, $match->{value}) }
+                : sub($step) { main::step_is($step, $match->@*) };
+            my $count = 0;
+            $opts{step_fault} = sub($step, $call) {
+                return undef if !$matches->($step) || $count >= ($times // 99);
+                $count++;
+                return $error;
+            };
+        }
+        my $self = bless {
+            m => {
+                ds => {},
+                snaps => {},
+                seq => 0,
+                subsystems => {},
+                ports => {},
+                hosts => {},
+                mounted => 1,
+                loaded => 1,
+                available => '1073741824',
+                used => '1048576',
+            },
+            calls => [],
+            violations => [],
+            faults => {}, # by call index: before, after, late, cut:<step> or lost:<step>
+            late => [], # calls that ssh gave up on, applied by land()
+            # a hash with after (call index) and mode (before, unreachable or failed)
+            read_fault => undef,
+            step_fault => undef, # sub ($step, $call) returning an error text
+            before_call => undef,
+            after_call => undef,
+            udev_delay => 0, # failing `test -b` polls after a zvol (re)appears
+            unbindable => {}, # port ids whose address is missing on the target
+            unreachable => 0,
+            secrets => [$KEY, $KEY_B],
+            %opts,
+        }, $class;
+        $self->{m}->{ds}->{$_} = { type => 'filesystem', props => {} } for $pools->@*;
+        return $self;
+    }
+
+    sub from_state($class, $state, %opts) {
+        my $self = $class->new(%opts);
+        $self->{m} = dclone($state);
+        return $self;
+    }
+
+    sub add_zvol($self, $name, %o) {
+        my %props;
+        @props{qw(proxmox:nvme-subsys proxmox:nvme-nsid proxmox:nvme-uuid)} = $o{identity}->@*
+            if $o{identity};
+        $self->{m}->{ds}->{$name} = {
+            type => 'volume',
+            props => \%props,
+            volsize => $o{volsize} // 1073741824,
+            origin => $o{origin} // '-',
+            devwait => 0,
+        };
+        return $self;
+    }
+
+    sub add_snapshot($self, $snapshot, %o) {
+        my ($name) = split /\@/, $snapshot;
+        my $ds = $self->{m}->{ds}->{$name};
+        $self->{m}->{snaps}->{$snapshot} = {
+            props => $o{props} // dclone($ds->{props}),
+            volsize => $ds->{volsize},
+            seq => ++$self->{m}->{seq},
+        };
+        return $self;
+    }
+
+    sub add_subsystem($self, $nqn, %o) {
+        $self->{m}->{subsystems}->{$nqn} = {
+            attr => {
+                attr_model => $o{model} // $MODEL,
+                attr_serial => $o{serial} // PVE::Storage::ZFSNVMePlugin::_nvmet_serial($nqn),
+                attr_allow_any_host => $o{allow_any_host} // '0',
+            },
+            acl => { map { $_ => 1 } ($o{acl} // [])->@* },
+            ns => {},
+        };
+        return $self;
+    }
+
+    sub add_namespace($self, $nqn, $nsid, $uuid, $dev, $enable = 1) {
+        $self->{m}->{subsystems}->{$nqn}->{ns}->{$nsid} = {
+            enable => "$enable",
+            device_path => $dev,
+            device_uuid => $uuid,
+            buffered_io => '0',
+        };
+        return $self;
+    }
+
+    sub add_port($self, $id, $address, $service, %o) {
+        $self->{m}->{ports}->{$id} = {
+            attr => {
+                addr_trtype => 'tcp',
+                addr_adrfam => $o{family} // 'ipv4',
+                addr_traddr => $address,
+                addr_trsvcid => "$service",
+            },
+            links => { map { $_ => 1 } ($o{links} // [])->@* },
+        };
+        return $self;
+    }
+
+    # nvmet creates the key attributes of a host world-readable
+    sub host_entry($key = undef) {
+        return { key => $key, mode => { map { $_ => '0644' } qw(dhchap_key dhchap_ctrl_key) } };
+    }
+
+    sub add_host($self, $hostnqn, $key = undef) {
+        $self->{m}->{hosts}->{$hostnqn} = host_entry($key);
+        return $self;
+    }
+
+    # a target restart: configfs is empty and, unless $loaded, nvmet is not loaded yet
+    sub reboot($self, $loaded = 0) {
+        my $m = $self->{m};
+        $m->{$_} = {} for qw(subsystems ports hosts);
+        $m->{loaded} = $loaded;
+        $_->{devwait} = 0 for grep { $_->{type} eq 'volume' } values $m->{ds}->%*;
+        return $self;
+    }
+
+    sub run($self, $scfg, $steps, $rendered, %opts) {
+        my $call = {
+            index => scalar($self->{calls}->@*),
+            op => $opts{op},
+            steps => dclone($steps),
+            rendered => $rendered,
+            timeout => $opts{timeout},
+            input => defined($opts{input}) ? 1 : 0,
+            locked => main::lock_held($scfg),
+            mutating => (grep { main::mutating_step($_) } $steps->@*) ? 1 : 0,
+            changing => main::changing($steps),
+            now => $main::NOW,
+        };
+        push $self->{calls}->@*, $call;
+        $self->audit($call, $opts{input});
+        $self->{before_call}->($self, $call) if $self->{before_call};
+        my $res = $self->execute($call, $steps, $opts{input});
+        $call->{rc} = $res->{rc};
+        $call->{err} = $res->{err};
+        $self->audit_text($call, $res->{err}, $res->{out}->@*);
+        $self->{after_call}->($self, $call) if $self->{after_call};
+        return $res;
+    }
+
+    # violations are recorded for the fake and for the whole run, which the last subtest checks
+    sub flag($self, @what) {
+        push $self->{violations}->@*, @what;
+        push @main::VIOLATIONS, @what;
+    }
+
+    sub violation($self, $what) {
+        $self->flag($what);
+        die "FAKEERR:protocol violation: $what\n";
+    }
+
+    sub err($message) {
+        die "FAKEERR:$message\n";
+    }
+
+    sub audit($self, $call, $input) {
+        my @bad;
+        my $op = $call->{op} // '';
+        push @bad, 'call without an operation label' if $op eq '';
+        for my $secret ($self->{secrets}->@*) {
+            push @bad, "key in the command of '$op'" if index($call->{rendered}, $secret) >= 0;
+        }
+        my $keys = grep { ref($_) eq 'HASH' && exists($_->{key}) } $call->{steps}->@*;
+        push @bad, "key write without stdin in '$op'" if $keys && !defined($input);
+        push @bad, "stdin without a key write in '$op'" if defined($input) && !$keys;
+        push @bad, "stdin is not a configured key in '$op'"
+            if defined($input) && !grep { $input eq "$_\n" } $self->{secrets}->@*;
+        push @bad, "target change without the target lock in '$op'"
+            if $call->{mutating} && !$call->{locked};
+        $self->flag(@bad);
+    }
+
+    sub audit_text($self, $call, @texts) {
+        for my $text (grep { defined } @texts) {
+            for my $secret ($self->{secrets}->@*) {
+                $self->flag("key in the output of '$call->{op}'") if index($text, $secret) >= 0;
+            }
+        }
+    }
+
+    # applies the calls that ssh gave up on, each chain stops at its first failing step
+    sub land($self) {
+        for my $late (splice($self->{late}->@*)) {
+            for my $step ($late->{steps}->@*) {
+                last if !eval { $self->step($step, $late->{input}); 1 };
+            }
+        }
+        return $self;
+    }
+
+    # A fault mode fails a call before it runs (rc 1), after it ran (the connection breaks, 255), at
+    # one of its steps (cut: the remote shell stops, lost: the rest of the chain still runs later),
+    # or ssh gives up on it while it runs to its end later (late, -1).
+    sub execute($self, $call, $steps, $input) {
+        my $closed = 'Connection to 192.0.2.10 closed by remote host.';
+        my $broken = { rc => 255, out => [], err => $closed };
+        my $no_route = 'ssh: connect to host 192.0.2.10: No route to host';
+        return { rc => 255, out => [], err => $no_route } if $self->{unreachable};
+        my $read_fault = $self->{read_fault};
+        if ($read_fault && !$call->{mutating} && $call->{index} > $read_fault->{after}) {
+            $self->{read_fault} = undef;
+            $call->{fault} = "read $read_fault->{mode}";
+            return { rc => 255, out => [], err => $no_route }
+                if $read_fault->{mode} eq 'unreachable';
+            return { rc => -1, out => [], err => 'ssh failed' } if $read_fault->{mode} eq 'failed';
+            return { rc => 1, out => [], err => 'injected read failure' };
+        }
+        my $mode = $self->{faults}->{ $call->{index} } // '';
+        $call->{fault} = $mode if $mode;
+        return { rc => 1, out => [], err => 'injected failure' } if $mode eq 'before';
+        if ($mode eq 'late') {
+            push $self->{late}->@*, { steps => dclone($steps), input => $input };
+            return { rc => -1, out => [], err => 'timeout' };
+        }
+        my ($cut) = $mode =~ /\Acut:([0-9]+)\z/;
+        my ($lost) = $mode =~ /\Alost:([0-9]+)\z/;
+        my @out;
+        for my $index (0 .. $steps->$#*) {
+            return $broken if defined($cut) && $index == $cut;
+            if (defined($lost) && $index == $lost) {
+                my @rest = $steps->@[$index .. $steps->$#*];
+                push $self->{late}->@*, { steps => dclone(\@rest), input => $input };
+                return $broken;
+            }
+            my $step = $steps->[$index];
+            my $error = $self->{step_fault} ? $self->{step_fault}->($step, $call) : undef;
+            if (!defined($error)) {
+                my @lines = eval { $self->step($step, $input) };
+                my $e = $@;
+                if (!$e) {
+                    push @out, @lines;
+                    next;
+                }
+                if ($e !~ s/\AFAKEERR://) {
+                    $self->flag("fake target error: $e");
+                    return { rc => 2, out => \@out, err => 'fake target error' };
+                }
+                chomp($error = $e);
+            }
+            return { rc => 1, out => \@out, err => $error eq '' ? 'exit code 1' : $error };
+        }
+        return $broken if $mode eq 'after';
+        return { rc => 0, out => \@out, err => '' };
+    }
+
+    sub step($self, $step, $input) {
+        if (ref($step) eq 'HASH' && exists($step->{write})) {
+            $self->write_attr($step->{write}, $step->{value});
+            return ();
+        }
+        if (ref($step) eq 'HASH') {
+            err('dd: error reading standard input') if !defined($input);
+            (my $key = $input) =~ s/\n\z//;
+            my @failed;
+            for my $path ($step->{key}->@*) {
+                eval { $self->write_key($path, $key) };
+                push @failed, $@ if $@;
+            }
+            die $failed[0] if @failed;
+            return ();
+        }
+        my ($command, @args) = $step->@*;
+        my $method = "cmd_$command";
+        $self->violation("command '$command'") if !$self->can($method);
+        return $self->$method(@args);
+    }
+
+    sub available($self) {
+        err("find: '$ROOT': No such file or directory")
+            if !$self->{m}->{mounted} || !$self->{m}->{loaded};
+    }
+
+    sub parts($self, $path) {
+        return () if $path !~ m{\A$RR/(.+)\z};
+        return split m{/}, $1;
+    }
+
+    sub zvol_name($self, $dev) {
+        return $dev =~ m{\A/dev/zvol/(.+)\z} ? $1 : undef;
+    }
+
+    sub block_device($self, $dev, $poll) {
+        my $name = $self->zvol_name($dev) // return 0;
+        my $ds = $self->{m}->{ds}->{$name} // return 0;
+        return 0 if $ds->{type} ne 'volume';
+        if ($ds->{devwait} > 0) {
+            $ds->{devwait}-- if $poll;
+            return 0;
+        }
+        return 1;
+    }
+
+    sub busy($self, $name) {
+        for my $subsys (values $self->{m}->{subsystems}->%*) {
+            return 1
+                if grep { $_->{enable} eq '1' && $_->{device_path} eq "/dev/zvol/$name" }
+                values $subsys->{ns}->%*;
+        }
+        return 0;
+    }
+
+    sub new_uuid($self) {
+        my $seq = ++$self->{m}->{seq};
+        return sprintf('%08x-dead-4000-8000-%012x', $seq, $seq);
+    }
+
+    sub write_attr($self, $path, $value) {
+        $self->available;
+        my @p = $self->parts($path) or $self->violation("write '$path'");
+        my $m = $self->{m};
+        if ($p[0] eq 'subsystems' && @p == 3) {
+            my $subsys = $m->{subsystems}->{ $p[1] } // err("$path: No such file or directory");
+            $self->violation("write '$path'")
+                if $p[2] !~ /\A(?:attr_model|attr_serial|attr_allow_any_host)\z/;
+            if ($p[2] eq 'attr_allow_any_host') {
+                err("$path: Invalid argument") if $value !~ /\A[01]\z/;
+                err("$path: Invalid argument") if $value eq '1' && $subsys->{acl}->%*;
+            }
+            $subsys->{attr}->{ $p[2] } = "$value";
+        } elsif ($p[0] eq 'subsystems' && @p == 5 && $p[2] eq 'namespaces') {
+            my $subsys = $m->{subsystems}->{ $p[1] } // err("$path: No such file or directory");
+            my $ns = $subsys->{ns}->{ $p[3] } // err("$path: No such file or directory");
+            my $attr = $p[4];
+            if ($attr eq 'enable') {
+                err("$path: Invalid argument") if $value !~ /\A[01]\z/;
+                err("$path: No such device")
+                    if $value eq '1'
+                    && $ns->{enable} ne '1'
+                    && !$self->block_device($ns->{device_path}, 0);
+                $ns->{enable} = "$value";
+            } elsif ($attr =~ /\A(?:device_path|device_uuid|buffered_io)\z/) {
+                err("$path: Device or resource busy") if $ns->{enable} eq '1';
+                if ($attr eq 'device_uuid') {
+                    err("$path: Invalid argument") if $value !~ $UUID_RE;
+                    $value = lc($value);
+                }
+                $ns->{$attr} = "$value";
+            } elsif ($attr eq 'revalidate_size') {
+                err("$path: Invalid argument") if $ns->{enable} ne '1' || $value ne '1';
+                $self->{revalidated}->{"$p[1]/$p[3]"}++;
+            } else {
+                $self->violation("write '$path'");
+            }
+        } elsif ($p[0] eq 'ports' && @p == 3) {
+            my $port = $m->{ports}->{ $p[1] } // err("$path: No such file or directory");
+            $self->violation("write '$path'")
+                if $p[2] !~ /\Aaddr_(?:trtype|adrfam|traddr|trsvcid)\z/;
+            err("$path: Permission denied") if $port->{links}->%*;
+            $port->{attr}->{ $p[2] } = "$value";
+        } else {
+            $self->violation("write '$path'");
+        }
+    }
+
+    sub write_key($self, $path, $key) {
+        $self->available;
+        my @p = $self->parts($path);
+        $self->violation("key write to '$path'")
+            if @p != 3 || $p[0] ne 'hosts' || $p[2] ne 'dhchap_key';
+        my $host = $self->{m}->{hosts}->{ $p[1] } // err("tee: $path: No such file or directory");
+        err("tee: $path: Invalid argument") if $key !~ /\ADHHC-1:/;
+        $self->violation("key write to the world-readable '$path'")
+            if ($host->{mode}->{ $p[2] } // '') ne '0600';
+        $host->{key} = $key;
+    }
+
+    sub cmd_mkdir($self, @paths) {
+        $self->available;
+        my $m = $self->{m};
+        for my $path (@paths) {
+            my @p = $self->parts($path) or $self->violation("mkdir '$path'");
+            my $exists = "mkdir: cannot create directory '$path': File exists";
+            my $missing = "mkdir: cannot create directory '$path': No such file or directory";
+            if ($p[0] eq 'subsystems' && @p == 2) {
+                err($exists) if $m->{subsystems}->{ $p[1] };
+                $m->{subsystems}->{ $p[1] } = {
+                    attr => {
+                        attr_model => 'Linux',
+                        attr_serial => substr(sha256_hex("serial $p[1]"), 0, 16),
+                        attr_allow_any_host => '0',
+                    },
+                    acl => {},
+                    ns => {},
+                };
+            } elsif ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+                my $subsys = $m->{subsystems}->{ $p[1] } // err($missing);
+                err("mkdir: cannot create directory '$path': Invalid argument")
+                    if $p[3] !~ /\A[0-9]+\z/ || $p[3] == 0 || $p[3] > 0xfffffffe;
+                err($exists) if $subsys->{ns}->{ $p[3] };
+                $subsys->{ns}->{ $p[3] } = {
+                    enable => '0',
+                    device_path => '(null)',
+                    device_uuid => $self->new_uuid,
+                    buffered_io => '0',
+                };
+            } elsif ($p[0] eq 'ports' && @p == 2 && $p[1] =~ /\A[0-9]+\z/) {
+                err($exists) if $m->{ports}->{ $p[1] };
+                $m->{ports}->{ $p[1] } = {
+                    attr => { map { ("addr_$_" => '') } qw(trtype adrfam traddr trsvcid) },
+                    links => {},
+                };
+            } elsif ($p[0] eq 'hosts' && @p == 2) {
+                err($exists) if $m->{hosts}->{ $p[1] };
+                $m->{hosts}->{ $p[1] } = host_entry();
+            } else {
+                $self->violation("mkdir '$path'");
+            }
+        }
+        return ();
+    }
+
+    sub cmd_chmod($self, $mode, @paths) {
+        $self->available;
+        $self->violation("chmod '$mode'") if $mode ne '0600';
+        for my $path (@paths) {
+            my @p = $self->parts($path);
+            $self->violation("chmod '$path'")
+                if @p != 3 || $p[0] ne 'hosts' || $p[2] !~ /\Adhchap_(?:ctrl_)?key\z/;
+            my $host = $self->{m}->{hosts}->{ $p[1] }
+                // err("chmod: cannot access '$path': No such file or directory");
+            $host->{mode}->{ $p[2] } = $mode;
+        }
+        return ();
+    }
+
+    sub cmd_rmdir($self, @paths) {
+        $self->available;
+        my $m = $self->{m};
+        my @errors;
+        for my $path (@paths) {
+            my @p = $self->parts($path) or $self->violation("rmdir '$path'");
+            my $fail = sub($why) { push @errors, "rmdir: failed to remove '$path': $why" };
+            if ($p[0] eq 'subsystems' && @p == 4 && $p[2] eq 'namespaces') {
+                my $subsys = $m->{subsystems}->{ $p[1] };
+                $fail->('No such file or directory')
+                    if !$subsys || !delete($subsys->{ns}->{ $p[3] });
+            } elsif ($p[0] eq 'subsystems' && @p == 2) {
+                my $subsys = $m->{subsystems}->{ $p[1] };
+                if (!$subsys) {
+                    $fail->('No such file or directory');
+                } elsif ($subsys->{ns}->%* || $subsys->{acl}->%*) {
+                    $fail->('Directory not empty');
+                } elsif (grep { $_->{links}->{ $p[1] } } values $m->{ports}->%*) {
+                    $fail->('Device or resource busy');
+                } else {
+                    delete $m->{subsystems}->{ $p[1] };
+                }
+            } elsif ($p[0] eq 'hosts' && @p == 2) {
+                if (!$m->{hosts}->{ $p[1] }) {
+                    $fail->('No such file or directory');
+                } elsif (grep { $_->{acl}->{ $p[1] } } values $m->{subsystems}->%*) {
+                    $fail->('Device or resource busy');
+                } else {
+                    delete $m->{hosts}->{ $p[1] };
+                }
+            } else {
+                $self->violation("rmdir '$path'");
+            }
+        }
+        err($errors[0]) if @errors;
+        return ();
+    }
+
+    sub cmd_rm($self, @paths) {
+        $self->available;
+        my $m = $self->{m};
+        my @errors;
+        for my $path (@paths) {
+            my @p = $self->parts($path);
+            my $missing = "rm: cannot remove '$path': No such file or directory";
+            if (@p == 4 && $p[0] eq 'ports' && $p[2] eq 'subsystems') {
+                my $port = $m->{ports}->{ $p[1] };
+                push @errors, $missing if !$port || !delete($port->{links}->{ $p[3] });
+            } elsif (@p == 4 && $p[0] eq 'subsystems' && $p[2] eq 'allowed_hosts') {
+                my $subsys = $m->{subsystems}->{ $p[1] };
+                push @errors, $missing if !$subsys || !delete($subsys->{acl}->{ $p[3] });
+            } else {
+                $self->violation("rm '$path'");
+            }
+        }
+        err($errors[0]) if @errors;
+        return ();
+    }
+
+    sub cmd_ln($self, $flag, $target, $link) {
+        $self->available;
+        my $m = $self->{m};
+        my @t = $self->parts($target);
+        my @l = $self->parts($link);
+        my $fail = sub($why) { err("ln: failed to create symbolic link '$link': $why") };
+        if (@l == 4 && $l[0] eq 'ports' && $l[2] eq 'subsystems') {
+            $self->violation("ln '$target' '$link'")
+                if @t != 2 || $t[0] ne 'subsystems' || $t[1] ne $l[3];
+            my $port = $m->{ports}->{ $l[1] } // $fail->('No such file or directory');
+            $fail->('No such file or directory') if !$m->{subsystems}->{ $t[1] };
+            $fail->('File exists') if $port->{links}->{ $l[3] };
+            my $a = $port->{attr};
+            $fail->('Invalid argument')
+                if $a->{addr_trtype} ne 'tcp'
+                || $a->{addr_adrfam} !~ /\Aipv[46]\z/
+                || $a->{addr_traddr} eq ''
+                || $a->{addr_trsvcid} eq '';
+            if (!$port->{links}->%*) { # the first link enables the port
+                $fail->('Cannot assign requested address') if $self->{unbindable}->{ $l[1] };
+                my @fields = qw(addr_trtype addr_adrfam addr_traddr addr_trsvcid);
+                my $address = join(' ', $a->@{@fields});
+                for my $id (keys $m->{ports}->%*) {
+                    my $other = $m->{ports}->{$id};
+                    next if $id eq $l[1] || !$other->{links}->%*;
+                    $fail->('Address already in use')
+                        if join(' ', $other->{attr}->@{@fields}) eq $address;
+                }
+            }
+            $port->{links}->{ $l[3] } = 1;
+        } elsif (@l == 4 && $l[0] eq 'subsystems' && $l[2] eq 'allowed_hosts') {
+            $self->violation("ln '$target' '$link'")
+                if @t != 2 || $t[0] ne 'hosts' || $t[1] ne $l[3];
+            my $subsys = $m->{subsystems}->{ $l[1] } // $fail->('No such file or directory');
+            $fail->('No such file or directory') if !$m->{hosts}->{ $t[1] };
+            $fail->('Invalid argument') if $subsys->{attr}->{attr_allow_any_host} eq '1';
+            $fail->('File exists') if $subsys->{acl}->{ $l[3] };
+            $subsys->{acl}->{ $l[3] } = 1;
+        } else {
+            $self->violation("ln '$target' '$link'");
+        }
+        return ();
+    }
+
+    sub cmd_test($self, $flag, $path) {
+        if ($flag eq '-b') {
+            err('') if !$self->block_device($path, 1);
+            return ();
+        }
+        $self->available;
+        my $m = $self->{m};
+        my @p = $self->parts($path);
+        my $found;
+        if (@p == 4 && $p[0] eq 'subsystems' && $p[2] eq 'allowed_hosts') {
+            $found = ($m->{subsystems}->{ $p[1] } // {})->{acl}->{ $p[3] };
+        } elsif (@p == 4 && $p[0] eq 'ports' && $p[2] eq 'subsystems') {
+            $found = ($m->{ports}->{ $p[1] } // {})->{links}->{ $p[3] };
+        } else {
+            $self->violation("test $flag '$path'");
+        }
+        err('') if !$found;
+        return ();
+    }
+
+    sub cmd_grep($self, $flag, $value, $path) {
+        $self->available;
+        my @p = $self->parts($path);
+        $self->violation("grep '$path'")
+            if @p != 3 || $p[0] ne 'subsystems' || $p[2] ne 'attr_allow_any_host';
+        my $subsys = $self->{m}->{subsystems}->{ $p[1] }
+            // err("grep: $path: No such file or directory");
+        err('') if $subsys->{attr}->{attr_allow_any_host} ne $value;
+        return ();
+    }
+
+    sub cmd_cat($self, $path) {
+        $self->violation("cat '$path'") if $path ne '/proc/mounts';
+        return (
+            'sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0',
+            'proc /proc proc rw,nosuid,nodev,noexec,relatime 0 0',
+            (
+                $self->{m}->{mounted}
+                ? ('configfs /sys/kernel/config configfs rw,relatime 0 0')
+                : ()
+            ),
+        );
+    }
+
+    sub cmd_mount($self, @args) {
+        err('mount: /sys/kernel/config: none already mounted on /sys/kernel/config.')
+            if $self->{m}->{mounted};
+        $self->{m}->{mounted} = 1;
+        return ();
+    }
+
+    sub cmd_modprobe($self, $module) {
+        $self->violation("modprobe '$module'") if $module ne 'nvmet_tcp';
+        $self->{m}->{loaded} = 1;
+        return ();
+    }
+
+    sub cmd_printf($self, @args) {
+        $self->violation('printf') if @args != 2 || $args[0] ne '%s\n' || $args[1] ne $MARKER;
+        return ($MARKER);
+    }
+
+    # the configfs read, the golden commands test pins its argv
+    sub cmd_env($self, @args) {
+        my @hosts = map { $args[$_ + 1] =~ m{\A$RR/hosts/([^/]+)/dhchap_key\z} ? ($1) : () }
+            grep { $args[$_] eq '-path' } 0 .. $#args;
+        $self->available;
+        return $self->configfs_lines(\@hosts);
+    }
+
+    sub configfs_lines($self, $hosts) {
+        my $m = $self->{m};
+        my (@dirs, @links, @attrs, @digests);
+        push @dirs, "D $ROOT", map { "D $ROOT/$_" } qw(hosts ports subsystems);
+        push @dirs, map { "D $ROOT/hosts/$_" } sort keys $m->{hosts}->%*;
+        for my $id (sort { $a <=> $b } keys $m->{ports}->%*) {
+            my $port = $m->{ports}->{$id};
+            push @dirs, "D $ROOT/ports/$id", "D $ROOT/ports/$id/subsystems";
+            push @links, map { "L $ROOT/ports/$id/subsystems/$_" } sort keys $port->{links}->%*;
+            push @attrs,
+                map { "$ROOT/ports/$id/$_:$port->{attr}->{$_}" } sort keys $port->{attr}->%*;
+        }
+        for my $nqn (sort keys $m->{subsystems}->%*) {
+            my $subsys = $m->{subsystems}->{$nqn};
+            my $S = "$ROOT/subsystems/$nqn";
+            push @dirs, "D $S", "D $S/allowed_hosts", "D $S/namespaces";
+            push @links, map { "L $S/allowed_hosts/$_" } sort keys $subsys->{acl}->%*;
+            push @attrs, map { "$S/$_:$subsys->{attr}->{$_}" } sort keys $subsys->{attr}->%*;
+            for my $id (sort { $a <=> $b } keys $subsys->{ns}->%*) {
+                my $ns = $subsys->{ns}->{$id};
+                push @dirs, "D $S/namespaces/$id";
+                push @attrs,
+                    map { "$S/namespaces/$id/$_:$ns->{$_}" }
+                    qw(buffered_io enable device_uuid device_path);
+            }
+        }
+        for my $hostnqn ($hosts->@*) {
+            my $host = $m->{hosts}->{$hostnqn} // next;
+            push @digests,
+                sha256_hex(($host->{key} // '') . "\n") . "  $ROOT/hosts/$hostnqn/dhchap_key";
+        }
+        return (@dirs, @links, @attrs, @digests);
+    }
+
+    sub cmd_zfs($self, $subcommand, @args) {
+        my $method = "zfs_$subcommand";
+        $self->violation("zfs $subcommand") if !$self->can($method);
+        return $self->$method(@args);
+    }
+
+    # Options with values are listed with 1, flags with 0.
+    sub options($self, $args, %spec) {
+        my %o;
+        my @rest = $args->@*;
+        while (@rest && $rest[0] =~ /\A-/) {
+            my $option = shift @rest;
+            if ($option eq '-Hp') {
+                $o{H} = $o{p} = 1;
+                next;
+            }
+            if ($option =~ /\A-d([0-9]+)\z/) {
+                $o{d} = [$1];
+                next;
+            }
+            my $name = substr($option, 1);
+            $self->violation("zfs option '$option'") if !exists($spec{$name});
+            if ($spec{$name}) {
+                push $o{$name}->@*, shift(@rest);
+            } else {
+                $o{$name} = 1;
+            }
+        }
+        return (\%o, @rest);
+    }
+
+    sub properties_of($self, $assignments) {
+        my %props;
+        for my $assignment (($assignments // [])->@*) {
+            $self->violation("zfs property '$assignment'") if $assignment !~ /\A([^=]+)=(.*)\z/;
+            $props{$1} = $2;
+        }
+        return \%props;
+    }
+
+    sub datasets_under($self, $target, $depth) {
+        my $m = $self->{m};
+        return () if !$m->{ds}->{$target};
+        return sort grep {
+            my $name = $_;
+            $name eq $target
+                || (index($name, "$target/") == 0
+                    && (() = substr($name, length($target)) =~ m{/}g) <= $depth)
+        } keys $m->{ds}->%*;
+    }
+
+    sub property($self, $name, $prop) {
+        my $m = $self->{m};
+        my $ds = $m->{ds}->{$name};
+        return ($ds->{type}, '-') if $prop eq 'type';
+        if ($prop =~ /:/) {
+            return ($ds->{props}->{$prop}, 'local') if defined($ds->{props}->{$prop});
+            my $parent = $name;
+            while ($parent =~ s{/[^/]+\z}{}) {
+                my $value = ($m->{ds}->{$parent} // last)->{props}->{$prop};
+                return ($value, "inherited from $parent") if defined($value);
+            }
+            return ('-', '-');
+        }
+        return ($m->{available}, '-') if $prop eq 'available';
+        return ($m->{used}, '-') if $prop eq 'used';
+        return ($ds->{volsize} // '-', '-') if $prop eq 'volsize';
+        return ('4096', '-') if $prop eq 'usedbydataset';
+        $self->violation("zfs property '$prop'");
+    }
+
+    sub zfs_get($self, @args) {
+        my ($o, $props, @targets) = $self->options(\@args, H => 0, p => 0, d => 1, t => 1, o => 1);
+        $self->violation('zfs get') if @targets != 1 || !$o->{H};
+        $self->violation('zfs get inventory')
+            if $props =~ /\Atype,proxmox:/
+            && !main::same(['get', @args], main::expected_inventory_read($targets[0]));
+        my $target = $targets[0];
+        my @fields = split /,/, ($o->{o} // ['name,property,value,source'])->[0];
+        my %types = map { $_ => 1 } split /,/, ($o->{t} // ['filesystem,volume'])->[0];
+        my @datasets = $self->datasets_under($target, $o->{d} ? $o->{d}->[0] : 0)
+            or err("cannot open '$target': dataset does not exist");
+        my @out;
+
+        for my $name (grep { $types{ $self->{m}->{ds}->{$_}->{type} } } @datasets) {
+            for my $prop (split /,/, $props) {
+                my ($value, $source) = $self->property($name, $prop);
+                my %row = (name => $name, property => $prop, value => $value, source => $source);
+                push @out, join("\t", map { $row{$_} } @fields);
+            }
+        }
+        return @out;
+    }
+
+    sub list_field($self, $row, $field) {
+        my $m = $self->{m};
+        return $row if $field eq 'name';
+        if (my $snap = $m->{snaps}->{$row}) {
+            return 1000 + $snap->{seq} if $field eq 'guid';
+            return 1700000000 + $snap->{seq} if $field eq 'creation';
+            $self->violation("zfs list snapshot field '$field'");
+        }
+        my $ds = $m->{ds}->{$row};
+        return $ds->{type} eq 'volume' ? $ds->{volsize} : '-' if $field eq 'volsize';
+        return $ds->{origin} // '-' if $field eq 'origin';
+        return $ds->{type} if $field eq 'type';
+        $self->violation("zfs list field '$field'");
+    }
+
+    sub zfs_list($self, @args) {
+        my ($o, @targets) =
+            $self->options(\@args, H => 0, p => 0, r => 0, d => 1, t => 1, o => 1, s => 1);
+        $self->violation('zfs list') if @targets != 1 || !$o->{H};
+        my $m = $self->{m};
+        my $target = $targets[0];
+        my @fields = split /,/, ($o->{o} // ['name'])->[0];
+        my %types = map { $_ => 1 } split /,/, ($o->{t} // ['filesystem,volume'])->[0];
+        my @rows;
+        if ($target =~ /\@/) {
+            err("cannot open '$target': dataset does not exist") if !$m->{snaps}->{$target};
+            @rows = ($target);
+        } else {
+            my $depth = $o->{d} ? $o->{d}->[0] : $o->{r} ? 1000 : 0;
+            my @datasets = $self->datasets_under($target, $depth)
+                or err("cannot open '$target': dataset does not exist");
+            if ($types{snapshot}) {
+                my %under = map { $_ => 1 } @datasets;
+                push @rows, sort { $m->{snaps}->{$a}->{seq} <=> $m->{snaps}->{$b}->{seq} }
+                    grep { $under{ (split /\@/)[0] } } keys $m->{snaps}->%*;
+            }
+            push @rows, grep { $types{ $m->{ds}->{$_}->{type} } } @datasets;
+        }
+        return map {
+            my $row = $_;
+            join("\t", map { $self->list_field($row, $_) } @fields)
+        } @rows;
+    }
+
+    sub zfs_create($self, @args) {
+        my ($o, @targets) = $self->options(\@args, s => 0, b => 1, o => 1, V => 1);
+        $self->violation('zfs create') if @targets != 1 || !$o->{V};
+        my $m = $self->{m};
+        my $name = $targets[0];
+        my ($parent) = $name =~ m{\A(.+)/[^/]+\z} or $self->violation('zfs create name');
+        $self->violation('zfs create size') if $o->{V}->[0] !~ /\A([0-9]+)k\z/;
+        my $size = $1 * 1024;
+        err("cannot create '$name': parent does not exist") if !$m->{ds}->{$parent};
+        err("cannot create '$name': dataset already exists") if $m->{ds}->{$name};
+        $m->{ds}->{$name} = {
+            type => 'volume',
+            props => $self->properties_of($o->{o}),
+            volsize => $size,
+            origin => '-',
+            devwait => $self->{udev_delay},
+            sparse => $o->{s} ? 1 : 0,
+            blocksize => $o->{b} ? $o->{b}->[0] : undef,
+        };
+        return ();
+    }
+
+    sub zfs_clone($self, @args) {
+        my ($o, $origin, $name, @extra) = $self->options(\@args, o => 1);
+        $self->violation('zfs clone') if @extra || !defined($name);
+        my $m = $self->{m};
+        my $snap = $m->{snaps}->{$origin} // err("cannot open '$origin': dataset does not exist");
+        err("cannot create '$name': dataset already exists") if $m->{ds}->{$name};
+        $m->{ds}->{$name} = {
+            type => 'volume',
+            props => $self->properties_of($o->{o}),
+            volsize => $snap->{volsize},
+            origin => $origin,
+            devwait => $self->{udev_delay},
+        };
+        return ();
+    }
+
+    sub zfs_destroy($self, @args) {
+        my ($o, $target, @extra) = $self->options(\@args, r => 0);
+        $self->violation('zfs destroy') if @extra || !defined($target);
+        my $m = $self->{m};
+        my $clones = sub($snapshot) {
+            return grep { ($_->{origin} // '-') eq $snapshot } values $m->{ds}->%*;
+        };
+        if ($target =~ /\@/) {
+            $self->violation('zfs destroy -r of a snapshot') if $o->{r};
+            err("could not find any snapshots to destroy; check snapshot names.")
+                if !$m->{snaps}->{$target};
+            err("cannot destroy snapshot $target: snapshot has dependent clones")
+                if $clones->($target);
+            delete $m->{snaps}->{$target};
+            return ();
+        }
+        $self->violation('zfs destroy without -r') if !$o->{r};
+        err("cannot open '$target': dataset does not exist") if !$m->{ds}->{$target};
+        err("cannot destroy '$target': dataset is busy") if $self->busy($target);
+        my @snaps = grep { index($_, "$target\@") == 0 } keys $m->{snaps}->%*;
+        err("cannot destroy '$target': filesystem has dependent clones")
+            if grep { $clones->($_) } @snaps;
+        delete $m->{snaps}->{$_} for @snaps;
+        delete $m->{ds}->{$target};
+        return ();
+    }
+
+    # Stricter than ZFS: user properties revert to their value at snapshot
+    # time, so the plugin must set the identity again after a rollback.
+    sub zfs_rollback($self, @args) {
+        $self->violation('zfs rollback') if @args != 1 || $args[0] !~ /\@/;
+        my $m = $self->{m};
+        my ($name) = split /\@/, $args[0];
+        my $snap = $m->{snaps}->{ $args[0] }
+            // err("cannot open '$args[0]': dataset does not exist");
+        err("cannot rollback to '$args[0]': more recent snapshots or bookmarks exist")
+            if grep { index($_, "$name\@") == 0 && $m->{snaps}->{$_}->{seq} > $snap->{seq} }
+            keys $m->{snaps}->%*;
+        err("cannot rollback '$name': dataset is busy") if $self->busy($name);
+        my $ds = $m->{ds}->{$name};
+        $ds->{props} = dclone($snap->{props});
+        $ds->{volsize} = $snap->{volsize};
+        $ds->{devwait} = $self->{udev_delay};
+        return ();
+    }
+
+    sub zfs_set($self, @args) {
+        my $target = pop @args;
+        $self->violation('zfs set') if !@args;
+        my $m = $self->{m};
+        my $object = $target =~ /\@/ ? $m->{snaps}->{$target} : $m->{ds}->{$target};
+        err("cannot open '$target': dataset does not exist") if !$object;
+        for my $assignment (@args) {
+            $self->violation("zfs set '$assignment'") if $assignment !~ /\A([^=]+)=(.*)\z/;
+            my ($prop, $value) = ($1, $2);
+            if ($prop eq 'volsize') {
+                $self->violation('zfs set volsize') if $value !~ /\A([0-9]+)k\z/;
+                $object->{volsize} = $1 * 1024;
+            } elsif ($prop =~ /:/) {
+                $object->{props}->{$prop} = $value;
+            } else {
+                $self->violation("zfs set '$prop'");
+            }
+        }
+        return ();
+    }
+
+    # Like OpenZFS, which renames the minor of a zvol that is open: an
+    # exported zvol is renamed under its namespace.
+    sub zfs_rename($self, @args) {
+        $self->violation('zfs rename') if @args != 2;
+        my ($old, $new) = @args;
+        my $m = $self->{m};
+        err("cannot open '$old': dataset does not exist") if !$m->{ds}->{$old};
+        err("cannot rename to '$new': dataset already exists") if $m->{ds}->{$new};
+        $m->{ds}->{$new} = delete $m->{ds}->{$old};
+        for my $snap (grep { index($_, "$old\@") == 0 } keys $m->{snaps}->%*) {
+            my $renamed = $new . substr($snap, length($old));
+            $m->{snaps}->{$renamed} = delete $m->{snaps}->{$snap};
+            for my $ds (values $m->{ds}->%*) {
+                $ds->{origin} = $renamed if ($ds->{origin} // '-') eq $snap;
+            }
+        }
+        $m->{ds}->{$new}->{devwait} = $self->{udev_delay};
+        return ();
+    }
+
+    sub zfs_snapshot($self, @args) {
+        $self->violation('zfs snapshot') if @args != 1 || $args[0] !~ /\A([^@]+)\@(.+)\z/;
+        my ($name, $snap) = ($1, $2);
+        err("cannot create snapshot '$args[0]': invalid character in name")
+            if $snap !~ /\A[A-Za-z0-9_.: -]+\z/;
+        my $m = $self->{m};
+        my $ds = $m->{ds}->{$name} // err("cannot open '$name': dataset does not exist");
+        err("cannot create snapshot '$args[0]': dataset already exists")
+            if $m->{snaps}->{ $args[0] };
+        $m->{snaps}->{ $args[0] } =
+            { props => dclone($ds->{props}), volsize => $ds->{volsize}, seq => ++$m->{seq} };
+        return ();
+    }
+}
+
+# The inventory read written down independently of the plugin code.
+my $INVENTORY_PROPS =
+    'type,proxmox:nvme-subsys,proxmox:nvme-nsid,proxmox:nvme-uuid,proxmox:nvme-last-nsid';
+
+sub expected_inventory_read($pool) {
+    return [
+        'get',
+        '-H',
+        '-p',
+        '-d',
+        '1',
+        '-t',
+        'filesystem,volume',
+        '-o',
+        'name,property,value,source',
+        $INVENTORY_PROPS,
+        $pool,
+    ];
+}
+
+sub secret_file($storeid) {
+    return "/etc/pve/priv/storage/$storeid.nvme-dhchap";
+}
+
+# The target part of a storage activation, with the key stored for the storage.
+sub activate($scfg = scfg(), $key = $KEY, $hostnqns = [@HOSTS], $portals = $PORTALS) {
+    local $FILES{ secret_file('st') } = $key;
+    return nv('_nvmet_activate_target', 'st', $scfg, $portals, $hostnqns, $key);
+}
+
+sub flow($fake, $code) {
+    local $FAKE = $fake;
+    local @LOCKS = ();
+    local @NESTED_LOCKS = ();
+    local @WARNINGS = ();
+    local @SYSFS_WRITES = ();
+
+    my $start = scalar($fake->{calls}->@*);
+    my $result = eval { $code->() };
+    my $error = $@;
+    my @calls = $fake->{calls}->@*;
+    return {
+        error => $error,
+        result => $result,
+        calls => [@calls[$start .. $#calls]],
+        locks => [@LOCKS],
+        nested => [@NESTED_LOCKS],
+        warnings => [@WARNINGS],
+        sysfs_writes => [@SYSFS_WRITES],
+    };
+}
+
+sub ops($res) {
+    return [map { $_->{op} } $res->{calls}->@*];
+}
+
+sub changes($res) {
+    return scalar(grep { $_->{changing} } $res->{calls}->@*);
+}
+
+# Our subsystem published on two ports to two hosts, no volumes yet.
+sub target_fake(%opts) {
+    my $fake = FakeTarget->new(pools => ['tank', 'other'], %opts);
+    $fake->add_host($_, $KEY) for @HOSTS;
+    $fake->add_subsystem($NQN, acl => [@HOSTS]);
+    $fake->add_port(1, '192.0.2.21', 4420, links => [$NQN]);
+    $fake->add_port(2, '192.0.2.22', 4420, links => [$NQN]);
+    return $fake;
+}
+
+sub add_volume($fake, $name, $nsid, $uuid, %o) {
+    $fake->add_zvol("tank/$name", identity => [$NQN, $nsid, $uuid]);
+    $fake->add_namespace($NQN, $nsid, $uuid, "/dev/zvol/tank/$name", $o{enable} // 1)
+        if !$o{unexported};
+    return $fake;
+}
+
+# A converged target with three owned volumes, an unowned leftover, a volume of another subsystem
+# in our pool, and a foreign subsystem that shares the first host and port 1.
+sub lifecycle_fake(%opts) {
+    my $fake = target_fake(%opts);
+    add_volume($fake, 'vm-100-disk-0', 1, $U{1});
+    add_volume($fake, 'vm-101-disk-0', 2, $U{2});
+    add_volume($fake, 'base-102-disk-0', 3, $U{3});
+    $fake->add_snapshot('tank/vm-100-disk-0@snap1');
+    $fake->add_snapshot('tank/base-102-disk-0@__base__');
+    $fake->add_zvol('tank/vm-900-disk-0');
+    $fake->add_zvol('tank/vm-901-disk-0', identity => [$FOREIGN_NQN, 7, $U{7}]);
+    $fake->add_zvol('other/foreign-disk', identity => [$FOREIGN_NQN, 1, $U{8}]);
+    $fake->add_subsystem(
+        $FOREIGN_NQN,
+        model => 'Linux',
+        serial => '0123456789abcdef',
+        acl => [$HOSTS[0]],
+    );
+    $fake->add_namespace($FOREIGN_NQN, 1, $U{8}, '/dev/zvol/other/foreign-disk');
+    $fake->{m}->{ports}->{1}->{links}->{$FOREIGN_NQN} = 1;
+    return $fake;
+}
+
+sub owned_volumes($m, $nqn = $NQN, $pool = 'tank') {
+    my %owned;
+    for my $name (sort keys $m->{ds}->%*) {
+        my $ds = $m->{ds}->{$name};
+        next if $ds->{type} ne 'volume' || $name !~ m{\A\Q$pool\E/[^/]+\z};
+        next if ($ds->{props}->{'proxmox:nvme-subsys'} // '') ne $nqn;
+        $owned{$name} = [map { $ds->{props}->{"proxmox:nvme-$_"} } qw(nsid uuid)];
+    }
+    return \%owned;
+}
+
+# Everything on the target that does not belong to the storage under test.
+# The last NSID handed out, on its pool, belongs to the storage.
+sub foreign_view($m, $port_ids, $nqn, $hostnqns, $pool = 'tank') {
+    my %ours = map { $_ => 1 } $hostnqns->@*;
+    my $dataset = sub($name) {
+        my $ds = $m->{ds}->{$name};
+        return $ds if $name ne $pool;
+        my %props = $ds->{props}->%*;
+        delete $props{'proxmox:nvme-last-nsid'};
+        return { $ds->%*, props => \%props };
+    };
+    return {
+        subsystems =>
+            { map { $_ => $m->{subsystems}->{$_} } grep { $_ ne $nqn } keys $m->{subsystems}->%* },
+        datasets => {
+            map { $_ => $dataset->($_) }
+            grep { ($m->{ds}->{$_}->{props}->{'proxmox:nvme-subsys'} // '') ne $nqn }
+                keys $m->{ds}->%*
+        },
+        hosts => { map { $_ => $m->{hosts}->{$_} } grep { !$ours{$_} } keys $m->{hosts}->%* },
+        ports => {
+            map {
+                my $port = $m->{ports}->{$_};
+                my @links = $port ? sort grep { $_ ne $nqn } keys $port->{links}->%* : ();
+                ($_ => $port ? [$port->{attr}, \@links] : undef)
+            } $port_ids->@*
+        },
+    };
+}
+
+# (i), (ii), (v) and (vi), checked after every call.
+sub online_violations($fake, $ctx) {
+    my $m = $fake->{m};
+    my $nqn = $ctx->{nqn};
+    my @bad;
+    if (my $subsys = $m->{subsystems}->{$nqn}) {
+        my $owned = owned_volumes($m, $nqn, $ctx->{pool});
+        my %identity = map { ("/dev/zvol/$_" => $owned->{$_}) } keys $owned->%*;
+        my %seen;
+        for my $id (sort keys $subsys->{ns}->%*) {
+            my $ns = $subsys->{ns}->{$id};
+            push @bad, "(ii) UUID $ns->{device_uuid} used by two namespaces"
+                if $seen{ lc($ns->{device_uuid}) }++;
+            next if $ns->{enable} ne '1';
+            my $want = $identity{ $ns->{device_path} };
+            push @bad, "(i) namespace $id exports $ns->{device_path} under another identity"
+                if !$want || $want->[0] ne $id || lc($want->[1]) ne lc($ns->{device_uuid});
+        }
+        if (grep { $_->{links}->{$nqn} } values $m->{ports}->%*) {
+            push @bad, '(v) published while any host may connect'
+                if $subsys->{attr}->{attr_allow_any_host} ne '0';
+            for my $hostnqn ($ctx->{hosts}->@*) {
+                push @bad, "(v) published without the ACL of $hostnqn"
+                    if !$subsys->{acl}->{$hostnqn};
+                push @bad, "(v) published without the key of $hostnqn"
+                    if (($m->{hosts}->{$hostnqn} // {})->{key} // '') ne $ctx->{key};
+            }
+        }
+    }
+    push @bad,
+        '(vi) objects of other storages changed'
+        if !same(
+            foreign_view($m, $ctx->{port_ids}, $nqn, $ctx->{hosts}, $ctx->{pool}),
+            $ctx->{foreign},
+        );
+    return @bad;
+}
+
+# (iii): owned identities stay valid, unique and attached to their volume.
+sub identity_violations($m, $ctx) {
+    my @bad;
+    my $owned = owned_volumes($m, $ctx->{nqn}, $ctx->{pool});
+    my (%nsids, %uuids);
+    for my $name (sort keys $owned->%*) {
+        my ($nsid, $uuid) = $owned->{$name}->@*;
+        push @bad, "(iii) invalid identity on $name"
+            if ($nsid // '') !~ /\A[1-9][0-9]*\z/ || ($uuid // '') !~ $UUID_RE;
+        push @bad, "(iii) NSID $nsid on two volumes" if $nsids{ $nsid // '' }++;
+        push @bad, "(iii) UUID $uuid on two volumes" if $uuids{ lc($uuid // '') }++;
+    }
+    for my $name (sort keys $ctx->{initial_owned}->%*) {
+        my $identity = join('/', $ctx->{initial_owned}->{$name}->@*);
+        my @holders = grep { join('/', $owned->{$_}->@*) eq $identity } keys $owned->%*;
+        next if !@holders && ($ctx->{may_vanish} // '') eq $name;
+        my %allowed = map { $_ => 1 } $name, ($ctx->{renames}->{$name} // ());
+        push @bad, "(iii) identity of $name lost" if @holders != 1 || !$allowed{ $holders[0] };
+    }
+    return @bad;
+}
+
+# A creation cut right after its mkdir leaves an unused subsystem with the
+# kernel's default model, which another tool could have created as well.
+# Activation refuses it until an administrator removes it.
+sub default_subsystem($m, $nqn) {
+    my $subsys = $m->{subsystems}->{$nqn} // return 0;
+    return
+        $subsys->{attr}->{attr_model} eq 'Linux'
+        && !$subsys->{ns}->%*
+        && !$subsys->{acl}->%*
+        && !grep { $_->{links}->{$nqn} } values $m->{ports}->%*;
+}
+
+# (iv): one more activation exports every owned volume exactly once.
+sub convergence_violations($fake, $ctx) {
+    my $res = flow($fake, sub { activate($ctx->{scfg}, $ctx->{key}, $ctx->{hosts}) });
+    if (my $error = $res->{error}) {
+        return ()
+            if $error =~ /not created by Proxmox VE/ && default_subsystem($fake->{m}, $ctx->{nqn});
+        return "(iv) activation afterwards failed: $error";
+    }
+    my $m = $fake->{m};
+    my $owned = owned_volumes($m, $ctx->{nqn}, $ctx->{pool});
+    my $subsys = $m->{subsystems}->{ $ctx->{nqn} } // return '(iv) subsystem missing';
+    my %want = map { $owned->{$_}->[0] => ["/dev/zvol/$_", lc($owned->{$_}->[1]), '1'] }
+        keys $owned->%*;
+    my %have = map {
+        my $ns = $subsys->{ns}->{$_};
+        ($_ => [$ns->{device_path}, lc($ns->{device_uuid}), $ns->{enable}])
+    } keys $subsys->{ns}->%*;
+    my @bad;
+    push @bad, '(iv) exported namespaces differ from the owned volumes' if !same(\%want, \%have);
+    # an interrupted port creation leaves an incomplete port that is ignored, a new one serves it
+    for my $portal ($PORTALS->@*) {
+        my ($address, $service) = $portal->@{qw(address port)};
+        push @bad, "(iv) not published on $address"
+            if !grep {
+                $_->{links}->{ $ctx->{nqn} }
+                && $_->{attr}->{addr_traddr} eq $address
+                && $_->{attr}->{addr_trsvcid} eq "$service"
+            } values $m->{ports}->%*;
+    }
+    return @bad;
+}
+
+sub run_case($initial, $ctx, $faults, $read_fault = undef) {
+    my $fake = FakeTarget->from_state($initial);
+    $fake->{faults} = $faults;
+    $fake->{read_fault} = $read_fault;
+    my @online;
+    $fake->{after_call} = sub($f, $call) {
+        push @online,
+            map { "call $call->{index} ($call->{op}): $_" } online_violations($f, $ctx);
+    };
+    my $res = flow($fake, $ctx->{action});
+    $res->{fake} = $fake;
+    $res->{online} = \@online;
+    $res->{faults} = { $faults->%*, ($read_fault ? (read => $read_fault->{mode}) : ()) };
+    return $res;
+}
+
+sub case_violations($ctx, $res) {
+    my $fake = $res->{fake};
+    my @bad;
+    push @bad, 'domain lock taken ' . scalar($res->{locks}->@*) . ' times'
+        if $res->{locks}->@* > 1;
+    push @bad, 'nested domain lock request' if $res->{nested}->@*;
+    push @bad, 'key in the error text' if grep { index($res->{error}, $_) >= 0 } $KEY, $KEY_B;
+
+    # The result must match the outcome: success only when the goal is reached. A flow whose only
+    # faults are lost replies (create and clone, which cannot settle one with a read) may fail after
+    # reaching its goal, but only with an unknown target state.
+    my @missing = $ctx->{done}->($fake->{m}, $res);
+    push @bad, map { "success without reaching the goal: $_" } @missing if $res->{error} eq '';
+    my @modes = values $res->{faults}->%*;
+    push @bad, "failure after reaching the goal: $res->{error}"
+        if $ctx->{lost_replies}
+        && $res->{error} ne ''
+        && $res->{error} !~ /the target state is unknown\n\z/
+        && !@missing
+        && @modes
+        && !grep { $_ ne 'after' } @modes;
+
+    # A call that ssh gave up on completes on the target afterwards. When the
+    # rest of it changes the target, the outcome was unknown.
+    if ($fake->{late}->@*) {
+        if (
+            grep {
+                grep { mutating_step($_) } $_->{steps}->@*
+            } $fake->{late}->@*
+        ) {
+            push @bad, "late call after a success" if $res->{error} eq '';
+            push @bad, "late call reported without an unknown state: $res->{error}"
+                if $res->{error} !~ /the target state is unknown\n\z/;
+        }
+        $fake->land;
+        push @bad, map { "after the late call: $_" } online_violations($fake, $ctx);
+    }
+    push @bad, identity_violations($fake->{m}, $ctx);
+    $fake->{faults} = {};
+    $fake->{read_fault} = undef;
+    push @bad, convergence_violations($fake, $ctx);
+    push @bad, $res->{online}->@*;
+    push @bad, map { "protocol: $_" } $fake->{violations}->@*;
+    return @bad;
+}
+
+# Fault sweep: every mutating call of a flow fails, and then every later mutating call of that run
+# fails as well, or the first read after it. After each run: (i) every enabled namespace of the
+# subsystem exports the zvol of its identity, (ii) no UUID is used twice, (iii) owned identities
+# are kept and unique, (iv) one more activation converges, (v) the subsystem is never published
+# before its ACLs, keys and allow_any_host=0, (vi) nothing of other storages changes, every change
+# ran under one domain lock and the result matches the outcome. (i), (ii), (v) and (vi) are checked
+# after every call, refusals have their own tests.
+sub sweep($name, $ctx) {
+    my $initial = dclone($ctx->{setup}->()->{m});
+    $ctx->{nqn} //= $NQN;
+    $ctx->{pool} //= 'tank';
+    $ctx->{hosts} //= [@HOSTS];
+    $ctx->{key} //= $KEY;
+    $ctx->{scfg} //= scfg();
+    $ctx->{initial_owned} = owned_volumes($initial, $ctx->{nqn}, $ctx->{pool});
+    $ctx->{port_ids} = [sort keys $initial->{ports}->%*];
+    $ctx->{foreign} =
+        foreign_view($initial, $ctx->{port_ids}, $ctx->{nqn}, $ctx->{hosts}, $ctx->{pool});
+
+    my $baseline = run_case($initial, $ctx, {});
+    is($baseline->{error}, '', "$name: succeeds without faults");
+    is_deeply([$ctx->{done}->($baseline->{fake}->{m}, $baseline)], [], "$name: reaches its goal");
+    is_deeply([case_violations($ctx, $baseline)], [], "$name: invariants hold without faults");
+
+    # A call fails in each mode of FakeTarget::execute, at each step of its chain. A second
+    # failure, in the compensation or the next round, is one that fails before or after its call,
+    # or the first read after the first failure fails or finds the target unreachable.
+    my $modes = sub($call) {
+        my @steps = 1 .. $call->{steps}->$#*;
+        return ('before', 'after', 'late', (map { "cut:$_" } @steps), map { "lost:$_" } @steps);
+    };
+    my @first = grep { $_->{mutating} } $baseline->{calls}->@*;
+    ok(scalar(@first), "$name: changes the target");
+    my ($runs, @failures) = (0);
+    for my $first (@first) {
+        my $k = $first->{index};
+        for my $mode ($modes->($first)) {
+            my $res = run_case($initial, $ctx, { $k => $mode });
+            $runs++;
+            my @later = grep { $_->{mutating} && $_->{index} > $k } $res->{calls}->@*;
+            push @failures, map { "call $k $mode: $_" } case_violations($ctx, $res);
+            for my $second (@later) {
+                my $j = $second->{index};
+                for my $again_mode (qw(before after)) {
+                    my $again = run_case($initial, $ctx, { $k => $mode, $j => $again_mode });
+                    $runs++;
+                    push @failures,
+                        map { "call $k $mode, call $j $again_mode: $_" }
+                        case_violations($ctx, $again);
+                }
+            }
+            for my $read_mode (qw(before unreachable)) {
+                my $read_fault = { after => $k, mode => $read_mode };
+                my $again = run_case($initial, $ctx, { $k => $mode }, $read_fault);
+                $runs++;
+                push @failures,
+                    map { "call $k $mode, next read $read_mode: $_" } case_violations($ctx, $again);
+            }
+        }
+    }
+    ok(!@failures, "$name: the invariants hold in $runs fault injections")
+        or diag(join("\n", @failures));
+}
+
+my $FIXTURE_ZFS = slurp("$FIXTURES/zfs_inventory.txt");
+my $FIXTURE_CFS = slurp("$FIXTURES/configfs_snapshot.txt");
+my $FIXTURE_DIGESTS = join('', map { "$KEY_SHA  $ROOT/hosts/$_/dhchap_key\n" } @FIXTURE_HOSTS);
+
+sub fixture_fake() {
+    my $fake = FakeTarget->new(pools => ['tank']);
+    $fake->add_host($_) for @FIXTURE_HOSTS;
+    $fake->add_subsystem($FIXTURE_NQN, acl => [@FIXTURE_HOSTS]);
+    $fake->add_port($_, "192.0.2.2$_", 4420, links => [$FIXTURE_NQN]) for 1, 2;
+    $fake->add_zvol('tank/vm-100-disk-0', identity => [$FIXTURE_NQN, 5, $FIXTURE_UUID5]);
+    $fake->add_zvol('tank/vm-100-cloudinit', identity => [$FIXTURE_NQN, 6, $FIXTURE_UUID6]);
+    $fake->add_namespace($FIXTURE_NQN, 5, $FIXTURE_UUID5, '/dev/zvol/tank/vm-100-disk-0');
+    $fake->add_namespace($FIXTURE_NQN, 6, $FIXTURE_UUID6, '/dev/zvol/tank/vm-100-cloudinit');
+    return $fake;
+}
+
+subtest 'the fake target answers in the formats of the fixture target' => sub {
+    my $fake = fixture_fake();
+    my @zfs = $fake->zfs_get(expected_inventory_read('tank')->@[1 .. 10]);
+    is(join('', map { "$_\n" } @zfs), $FIXTURE_ZFS, 'the ZFS inventory equals the fixture');
+    my $cfs = join('', map { "$_\n" } $fake->configfs_lines([]));
+    is_deeply(
+        nv('_nvmet_parse_configfs', $cfs),
+        nv('_nvmet_parse_configfs', $FIXTURE_CFS),
+        'the configfs read parses to the fixture',
+    );
+};
+
+done_testing();
-- 
2.54.0.windows.1




  parent reply	other threads:[~2026-11-26 15:12 UTC|newest]

Thread overview: 16+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-26 15:09 [PATCH storage v5 00/13] add ZFS over NVMe/TCP storage plugin Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 01/13] zfsnvme: add target state parsing and planning Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 02/13] zfsnvme: add the target transactions Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 03/13] zfsnvme: add storage configuration and volume methods Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 04/13] zfsnvme: connect the nodes and register the plugin Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 05/13] api: san luns: count zfsnvme storages as owners of their subsystem Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 06/13] api: config: check the cluster version before the first zfsnvme storage Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 07/13] test: zfsnvme: add configuration and volume tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 08/13] test: zfsnvme: add node side tests Joaquin Varela
2026-11-26 15:09 ` Joaquin Varela [this message]
2026-11-26 15:09 ` [PATCH storage v5 10/13] test: zfsnvme: test the target parsers and planners Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 11/13] test: zfsnvme: test the target flows Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 12/13] test: zfsnvme: add a fault sweep, renderer and taint tests Joaquin Varela
2026-11-26 15:09 ` [PATCH storage v5 13/13] zfsnvme: wait up to 30 seconds for the shared storage lock Joaquin Varela
2026-11-26 15:10 ` [PATCH docs v5] storage: document ZFS over NVMe/TCP Joaquin Varela
2026-11-26 15:11 ` [PATCH manager v5] ui: storage: add ZFS over NVMe/TCP editor Joaquin Varela

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20261126150956.310593-10-joaquinvarela@neatech.ar \
    --to=joaquinvarela@neatech.ar \
    --cc=pve-devel@lists.proxmox.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal