lib/App/karr/Git.pm

filter: Statementstmt 94.4% 34 / 36 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 12 / 12 Podpod n/a totaltotal 95.8% 46 / 48 CC 1 SCAR 0.2
CC
1
Cov
94%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« blib/lib/App/karr/Cmd/Context.pm ↑ Summary blib/lib/App/karr/Foundation.pm »
1 # ABSTRACT: Git operations for karr sync (native via Git::Native + libgit2, with a git-CLI transport fallback)
2  
3 package App::karr::Git;
4 our $VERSION = '0.602';
5 39 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 39 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 39 ▶use Path::Tiny qw( path );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 39 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 39 ▶use IPC::Open3 qw( open3 );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 39 ▶use IO::Select;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 39 ▶use Symbol qw( gensym );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 39 ▶use Errno qw( EINTR );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 39 ▶use POSIX qw( WNOHANG );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 39 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
15 39 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 0 ▶use Git::Libgit2 qw(
Subroutine BEGIN: called CC=1 SCAR=2.6
17 GIT_ELOCKED
18 GIT_OPT_SET_SERVER_CONNECT_TIMEOUT
19 GIT_OPT_SET_SERVER_TIMEOUT
20 0 );
21 use Git::Libgit2::FFI ();
22 use App::karr::Error qw( clean_error );
23 use App::karr::Encoding qw(
24 BOARD_ENCODING_VERSION
25 to_octets from_octets yaml_dump yaml_load repair_mojibake
26 );
27 use Git::Native;
28 use Git::Native::Signature;
29 use Git::Native::Credential;
30 use App::karr::Task;
31  
32  
33 sub new {
34 my ( $class, %args ) = @_;
35 return bless {
36 dir => $args{dir} // '.',
37 }, $class;
38 }
39  
40  
41 sub dir {
42 my ($self) = @_;
43 return path( $self->{dir} );
44 }
45  
46  
47 # The libgit2 exception text from the most recent remote operation that failed
48 # (fetch/push/pull). Native operations have no shell exit code, so callers
49 # report this instead of $?. When the git-CLI transport fallback ran (see
50 # _cli_transport below), this instead carries the real git-CLI stderr.
51 sub last_error {
52 my ($self) = @_;
53 return $self->{_last_error};
54 }
55  
56  
57 # Ref writes and deletes performed in this process. App::karr::SyncGuard reads
58 # it on the die path -- where no push has succeeded by definition -- to tell
59 # "the command died before writing anything" (nothing to push, stay quiet)
60 # apart from "local refs changed and never reached the remote" (say so).
61 #
62 # Deliberately a package scalar rather than per-object state. The guard reads
63 # the count from DESTROY during global destruction, and perl tears that phase
64 # down in two passes: sv_clean_objs() destroys every blessed object first, then
65 # sv_clean_all() frees everything else. So when DESTROY runs, another object may
66 # already be gone while a plain non-object SV like this one is still intact.
67 # Reading the count off $git made the quiet/loud decision a coin flip -- over 60
68 # identical runs of one failing command $git was still there 52 times and
69 # already reaped 8, so 13% of plain usage errors printed sync advice for a
70 # board that had never been written to (#34).
71 our $WRITES = 0;
72  
73 sub pending_writes {
74 return $WRITES;
75 }
76  
77  
78 # ----- Native repository handle (lazy) -----
79  
80 # libgit2 is reached through FFI::Platypus, and both its type parser and
81 # FFI::CheckLib's library-search tables are package-level state. Perl frees
82 # that state during global destruction in no defined order, and re-entering it
83 # there does not fail cleanly: FFI::CheckLib re-runs its search against
84 # already-undefined globals and FFI::Platypus::TypeParser::Version1::parse
85 # recurses without bound, allocating around 700 MB/s until the machine is out
86 # of memory (#34 -- observed at 53 GB RSS on a 62 GB box, killable only from
87 # outside).
88 #
89 # karr is built to be driven by unattended agents, so that failure mode is not
90 # survivable. _repo and is_repo are the gate: every native operation reachable
91 # from a teardown path goes through them, and every caller already treats a
92 # false _repo as "no usable repository", so the runaway degrades into an
93 # ordinary failure with last_error set. (validate_helper_ref calls libgit2
94 # directly, but nothing destroys helper refs during teardown.)
95 sub _in_global_destruction {
96 return ${^GLOBAL_PHASE} eq 'DESTRUCT' ? 1 : 0;
97 }
98  
99 sub _repo {
100 my ($self) = @_;
101 if ( _in_global_destruction() ) {
102 $self->{_last_error} =
103 'refused: libgit2 is not re-entrant during global destruction';
104 return undef;
105 }
106 return $self->{_repo} if $self->{_repo};
107 return undef unless $self->is_repo;
108 $self->{_repo} = Git::Native->open_ext( $self->dir->stringify );
109 _apply_native_transport_timeouts();
110 return $self->{_repo};
111 }
112  
113 # KARR_TRANSPORT_TIMEOUT used to bound _cli_transport and nothing else, and the
114 # CLI only ever runs after the native transport has returned -- so it bounded
115 # the one path that could not hang while leaving the one that could unbounded.
116 # A peer that completes the TCP handshake and then never speaks kept every karr
117 # command in a blocking read inside libgit2 forever (#170; measured at 300 s
118 # with no end in sight, the process asleep at ~1.8% CPU). No callback fires in
119 # that state, so nothing on the Perl side can interrupt it -- a Perl signal
120 # handler is not delivered while the interpreter sits in a C call.
121 #
122 # libgit2 1.8 grew two globals for exactly this. They are milliseconds, and 0
123 # means no limit, which is what KARR_TRANSPORT_TIMEOUT=0 already meant, so one
124 # knob now governs both transports. As a bound this is weaker than the CLI's:
125 # there the timeout is the whole run's wall clock, here it is one read or
126 # write, so nothing that finishes under the CLI rule can fail under this one.
127 #
128 # git_libgit2_opts mutates process-global libgit2 state, not the repository
129 # (the same story Git::Native->set_config_search_path tells about
130 # GIT_OPT_SET_SEARCH_PATH), hence a package-level latch rather than per-object
131 # state. It is keyed on the value so a caller that changes the environment
132 # mid-process -- tests do -- is not answered from a stale global.
133 #
134 # Every transport libgit2 speaks honours these, ssh:// included -- from 1.9.3
135 # up. Below that the ssh reads went through a libssh2 loop that retried past
136 # the socket timeout, so a peer that accepted the connection and then went
137 # quiet hung the native path with no deadline in sight (measured: still
138 # blocked after 75 s -- #174). karr answers that through the dependency rather
139 # than through a version test here: cpanfile requires an Alien::Libgit2 whose
140 # pkg-config floor is 1.9.3, so the broken half is not a library karr runs on.
141 # Measured on 1.9.3 against a silent listener: a native ssh:// ref listing
142 # comes back at the configured timeout (1.5 s -> 1.51 s).
143 my $NATIVE_TRANSPORT_TIMEOUT;
144  
145 sub _apply_native_transport_timeouts {
146 my $seconds = _transport_timeout();
147 return if defined $NATIVE_TRANSPORT_TIMEOUT
148 && $NATIVE_TRANSPORT_TIMEOUT == $seconds;
149 return _set_native_transport_timeouts($seconds);
150 }
151  
152 # The same write without the latch check, for the one caller whose budget is
153 # not the transport's: remote_has_board lowers the globals to the probe's share
154 # for one call and puts them back through _apply_native_transport_timeouts
155 # afterwards. The latch is updated here so the restore is a no-op when the two
156 # values coincide.
157 sub _set_native_transport_timeouts {
158 my ($seconds) = @_;
159  
160 # A sub-millisecond budget must not round down to 0 -- that is libgit2's
161 # "no limit", the exact opposite of what was asked for.
162 my $ms = int( $seconds * 1000 );
163 $ms = 1 if $seconds > 0 && $ms < 1;
164  
165 # Both options were appended to libgit2's option enum in 1.8. An older
166 # library answers -1 ("invalid option") and does nothing, leaving the
167 # native transport as unbounded as it was before. cpanfile's floor is
168 # 1.9.3, well above that, and it holds even where the system library is
169 # older -- Debian bookworm's 1.5.1, which karr's own CI installs, is
170 # rejected by Alien::Libgit2's pkg-config check and replaced by a source
171 # build. So this is only reachable by forcing an older library in on
172 # purpose, and a warning would not be worth it there either: it would fire
173 # for purely local work, where no socket is involved and nothing can hang,
174 # and the CLI fallback still bounds the one path that reaches a network.
175 Git::Libgit2::FFI::git_libgit2_opts_int( $_, $ms )
176 for GIT_OPT_SET_SERVER_CONNECT_TIMEOUT, GIT_OPT_SET_SERVER_TIMEOUT;
177  
178 $NATIVE_TRANSPORT_TIMEOUT = $seconds;
179 return;
180 }
181  
182 # The identity is read from git config once per process. The timestamp is not,
183 # and that is the point: libgit2 stamps a signature at the moment the
184 # git_signature is allocated, so a signature cached for the life of the process
185 # made every commit it ever wrote carry the time of the first one. In a
186 # short-lived CLI run that is invisible; in a long-running driver
187 # (karr-foundation draining boards for hours) every ref it wrote was
188 # backdated to process start.
189 #
190 # App::karr::Lock reads exactly this timestamp back -- via commit_time below --
191 # to decide whether a lock is stale, so a cached one would have made every lock
192 # taken by a long-running agent look expired the instant it was written (#45).
193 sub _signature {
194 my ($self) = @_;
195 unless ( $self->{_sig_identity} ) {
196 $self->_repo or return;
197 $self->{_sig_identity} = {
198 name => $self->git_user_name || 'karr',
199 email => $self->git_user_email || 'karr@localhost',
200 };
201 }
202 return Git::Native::Signature->new(
203 %{ $self->{_sig_identity} },
204 when => time,
205 offset => 0,
206 );
207 }
208  
209 # Committer time of the commit a ref points at, as a Unix epoch. Takes the OID
210 # rather than the ref name so the caller can judge the age of the same revision
211 # it is about to guard a compare-and-swap against: reading the ref a second time
212 # here would let it move in between, and a lock steal decided on one revision
213 # but applied to another silently evicts a live holder.
214 sub commit_time {
215 my ( $self, $oid ) = @_;
216 return undef unless defined $oid && length $oid;
217 my $repo = $self->_repo or return undef;
218 return try { $repo->commit($oid)->time } catch { undef };
219 }
220  
221  
222 # ----- Repo discovery -----
223  
224 sub is_repo {
225 my ($self) = @_;
226 return 0 if _in_global_destruction();
227 my $ok = try {
228 # open_ext walks up to find a .git; throws on miss.
229 Git::Native->open_ext( $self->dir->stringify );
230 1;
231 } catch { $self->{_last_error} = "$_"; 0 };
232 return $ok;
233 }
234  
235  
236 sub repo_root {
237 my ($self) = @_;
238 my $repo = $self->_repo or return undef;
239 # workdir is undef for bare repos; in that case fall back to gitdir.
240 my $root = $repo->workdir // $repo->gitdir;
241 $root =~ s{/+\z}{};
242 return path($root);
243 }
244  
245  
246 # ----- Working-tree file status -----
247  
248 # libgit2's status flags. A path git carries in the index or HEAD reports
249 # anything *except* these two: GIT_STATUS_WT_NEW is "untracked" and
250 # GIT_STATUS_IGNORED is "untracked and matched by a .gitignore rule". An
251 # unmodified tracked file reports GIT_STATUS_CURRENT (0), and ignore rules do
252 # not apply to tracked files -- which is the case that matters here, because
253 # `karr init` puts tasks/ and config.yml into .gitignore.
254 use constant GIT_STATUS_WT_NEW => 0x0080;
255 use constant GIT_STATUS_IGNORED => 0x4000;
256  
257 # Resolve $path to a string relative to the WORK TREE ROOT -- repo_root, never
258 # ->dir. That is the form status_for_path (is_tracked), the index
259 # (is_tracked_under) and a git-CLI pathspec all want: root-relative with /
260 # separators, exactly as `git ls-files` prints them. The two happen to be the
261 # same string whenever ->dir is the root, which is all BoardDiscovery ever
262 # builds, so a consumer that resolves from ->dir instead looks correct until
263 # something constructs this class on a subdirectory (#113). Every route below
264 # therefore resolves from the root: libgit2 does so by itself, and _run_git is
265 # pinned to it.
266 #
267 # The root itself is `.`, which is a pathspec git understands but NOT a path
268 # the index can hold -- entries are stored as `tasks/a.md`, never `./tasks/a.md`
269 # (#114). A consumer that asks the index has to spell that case out.
270 #
271 # Both ends go through the containing directory -- the path itself may not
272 # exist yet -- so a symlinked work tree does not make every path look like it
273 # escapes. Undef when the repo has no work tree, or $path resolves outside it.
274 sub _relative_to_root {
275 my ( $self, $path ) = @_;
276 my $root = $self->repo_root or return undef;
277 $path = path($path)->absolute;
278 my $parent = try { $path->parent->realpath } catch { undef } or return undef;
279 my $base = try { $root->realpath } catch { $root };
280 my $rel = $parent->child( $path->basename )->relative($base)->stringify;
281 return undef if $rel =~ m{\A\.\.(?:/|\z)}; # outside the work tree
282 return $rel;
283 }
284  
285 sub is_tracked {
286 my ( $self, $file ) = @_;
287 my $repo = $self->_repo or return 0;
288 my $rel = $self->_relative_to_root($file);
289 return 0 unless defined $rel;
290  
291 # Throws GIT_ENOTFOUND for a path git has never heard of and that is not on
292 # disk either; that is simply "not tracked".
293 my $status = try { $repo->status_for_path($rel) } catch { undef };
294 return 0 unless defined $status;
295 return $status & ( GIT_STATUS_WT_NEW | GIT_STATUS_IGNORED ) ? 0 : 1;
296 }
297  
298  
299 sub is_tracked_under {
300 my ( $self, $path ) = @_;
301 my $rel = $self->_relative_to_root($path);
302 return 0 unless defined $rel;
303  
304 # Answers against the index and against $path as a prefix, neither of
305 # which is_tracked above can do. libgit2's status_for_path takes one file
306 # and, being a working-tree comparison, cannot see a path git tracks but
307 # that is currently missing from disk -- rm'd, not yet committed (#104).
308 # The index carries the entry either way, and Git::Native::Index asks it as
309 # a path question: the exact entry first, then "$rel/" as a prefix, so a
310 # directory answers for everything below it without `tasks` being answered
311 # by a tracked `tasksfoo.txt` (#107).
312 #
313 # Every ->index re-reads the index file from disk rather than handing back
314 # a cached one, which is what makes this safe in a checkout several agents
315 # are staging and committing in.
316 #
317 # `.` -- the work tree root -- is the one thing the index cannot be asked
318 # as a path: no entry is stored with a leading `./`, so neither the exact
319 # path nor the `./` prefix can ever match and the answer came back 0 for a
320 # repository full of tracked files (#114). At the root the question is
321 # simply whether the index holds anything at all, which is what the CLI's
322 # `ls-files -- .` answers there too.
323 my $native = try {
324 my $repo = $self->_repo or return undef;
325 my $index = $repo->index;
326 return $index->entrycount ? 1 : 0 if $rel eq '.';
327 $index->is_tracked_under($rel) ? 1 : 0;
328 } catch { $self->{_last_error} = "$_"; undef };
329 return $native if defined $native;
330  
331 # Reached only when libgit2 could not answer -- an index it refuses to
332 # read, or a Git::Native older than the `index` accessor. `git ls-files`
333 # reads the same index and matches a bare directory name as a prefix over
334 # everything under it, so it answers the same question for a file or a
335 # directory alike -- and $rel is a root-relative pathspec, which is why
336 # _run_git resolves it from the work tree root rather than from ->dir.
337 # Without a `git` on PATH there is nothing left to ask, and an unanswered
338 # question is reported as "not tracked" -- the same
339 # not-tracked-as-far-as-we-can-tell that is_tracked returns for a
340 # repository it cannot open.
341 my $run = $self->_run_git( 'ls-files', '-z', '--', $rel );
342 return 0 unless $run->{failure} eq '' && ( $run->{status} >> 8 ) == 0;
343 return length $run->{out} ? 1 : 0;
344 }
345  
346  
347 # ----- User identity (read via native config, not via CLI) -----
348  
349 sub _config_string {
350 my ( $self, $key ) = @_;
351 my $repo = $self->_repo or return '';
352 my $val = try { $repo->config_string($key) } catch { undef };
353 return defined $val ? from_octets($val) : '';
354 }
355  
356 sub git_user_email {
357 my ($self) = @_;
358 return $self->_config_string('user.email');
359 }
360  
361  
362 sub git_user_name {
363 my ($self) = @_;
364 return $self->_config_string('user.name');
365 }
366  
367  
368 sub git_user_identity {
369 my ($self) = @_;
370 my $name = $self->git_user_name;
371 my $email = $self->git_user_email;
372 return "$name <$email>" if $name && $email;
373 return $email || $name || '';
374 }
375  
376  
377 # ----- Ref name validation -----
378  
379 sub normalize_ref_name {
380 my ( $self, $ref ) = @_;
381 defined $ref or die "Ref name is required\n";
382 $ref =~ s{^/+}{};
383 return $ref =~ m{^refs/} ? $ref : "refs/$ref";
384 }
385  
386  
387 # Namespaces a helper ref may be read from but not written to.
388 #
389 # refs/karr-foundation/ as a whole stays reachable on purpose: this fleet
390 # design's own document lives at refs/karr-foundation/spec/fleet-execution.md
391 # and was put there with `karr set-refs`, so blocking the namespace outright
392 # would break the very artifact it was chosen for. The two subtrees
393 # karr-foundation writes itself are different. App::karr::Foundation::ChainStore
394 # keeps a schema, a DAG invariant and compare-and-swap updates there, while
395 # `karr set-refs` writes last-writer-wins and joins its arguments with a single
396 # space -- so a hand-written step would either clobber one another tick had just
397 # claimed, or land as a payload that no longer parses as a step, and the runner
398 # would then treat the wreck as the plan. The stale-precheck guard protects
399 # against an out-of-date chain, not against a malformed one.
400 #
401 # The question mailbox (App::karr::Foundation::Questions) joins them, and the
402 # argument for it is the second half of the same one rather than the first. A
403 # person answering a question by hand is an *intended* writer here -- that is
404 # the whole design -- but `karr set-refs` is not the hand they would use: the
405 # payload it can produce is its arguments joined by a space, and a question or
406 # an answer is a YAML mapping, so every hand-written one would land as a ref
407 # the mailbox skips with a warning while the person who wrote it believes the
408 # question is answered. `karr-foundation answer <id>` is the door built for
409 # that, it validates the answer against the options it was offered, and it is
410 # create-only so two answers cannot silently become one.
411 #
412 # Reading stays open, because reading cannot corrupt anything and looking at a
413 # step, a run log or a question with `karr get-refs` is exactly how you debug a
414 # chain.
415 use constant HELPER_READ_ONLY => (
416 'refs/karr-foundation/chain/',
417 'refs/karr-foundation/log/',
418 'refs/karr-foundation/questions/',
419 );
420  
421 sub validate_helper_ref {
422 my ( $self, $ref, %opt ) = @_;
423 my $full_ref = $self->normalize_ref_name($ref);
424  
425 my @blocked = (
426 'refs/heads/',
427 'refs/tags/',
428 'refs/remotes/',
429 'refs/bisect/',
430 'refs/replace/',
431 'refs/karr/',
432 # Pick locks (App::karr::Lock) and the deletion tombstones a push
433 # publishes from (TOMBSTONE_ROOT). Locks were moved out of refs/karr/
434 # so that no refspec could publish them (#93); `karr set-refs` names a
435 # ref and pushes it, so leaving it able to reach that namespace would
436 # put the same hole back one command over.
437 'refs/karr-local/',
438 # The remote-tracking mirror (MIRROR_ROOT) and the parking lot for the
439 # local side of a conflict (CONFLICT_ROOT) -- spelled out rather than
440 # named, because both constants are declared further down the file and
441 # `use constant` is only visible from its textual point on.
442 #
443 # The mirror is the third door of the same hole (#199): every pull
444 # decides what a ref means by comparing it against the mirror, so a
445 # hand-written entry there does not corrupt a payload, it makes the
446 # reconciliation reach the wrong one of its four conclusions -- a card
447 # comes out as "the remote deleted this" and is removed locally, or as
448 # "unpushed local work" and is forced over the remote's newer version
449 # (#154). Nothing legitimate writes it: App::karr::Git owns it end to
450 # end. The conflict parking lot is only read back by a person, but it
451 # is no one else's to write either, and a fabricated entry there is a
452 # card that looks like it was displaced by a conflict that never
453 # happened.
454 'refs/karr-remote/',
455 'refs/karr-conflict/',
456 );
457  
458 for my $prefix (@blocked) {
459 die "Ref '$full_ref' is in a protected namespace\n"
460 if index( $full_ref, $prefix ) == 0;
461 }
462 die "Ref '$full_ref' is in a protected namespace\n"
463 if $full_ref eq 'refs/stash' || index( $full_ref, 'refs/stash/' ) == 0;
464  
465 if ( $opt{for_write} ) {
466 for my $prefix (HELPER_READ_ONLY) {
467 die "Ref '$full_ref' is written by karr-foundation itself and "
468 . "cannot be set by hand (get-refs can still read it)\n"
469 if index( $full_ref, $prefix ) == 0;
470 }
471 }
472  
473 # Native validity check via Git::Native.
474 die "Ref '$full_ref' is not a valid git ref name\n"
475 unless Git::Native->reference_name_is_valid($full_ref);
476  
477 return $full_ref;
478 }
479  
480  
481 # ----- Ref CRUD (the hotspot — was 4 fork/exec per write_ref) -----
482  
483 # How many times a contended ref write is re-attempted before karr gives up,
484 # and the backoff between attempts. Contention here is measured in the time it
485 # takes libgit2 to take refs/<name>.lock, write and rename -- microseconds --
486 # so a few milliseconds of randomised sleep is enough to break up a pile-up.
487 # The randomisation is the point: a fixed delay makes every loser wake up
488 # together and collide again.
489 #
490 # Bounded on purpose. karr is driven by unattended agents, and a write loop
491 # that can spin forever on a genuinely wedged ref is worse than one that fails
492 # with something the agent can report.
493 use constant CAS_ATTEMPTS => 32;
494 use constant CAS_BACKOFF_STEP => 0.001; # seconds, times the attempt number
495 use constant CAS_BACKOFF_CAP => 0.010; # ...but never longer than this
496 use constant CAS_BACKOFF_JITTER => 0.005;
497  
498 # Run $attempt until it commits to an answer, with backoff in between.
499 #
500 # $attempt returns the empty list to mean "another writer got in first, read
501 # again and retry"; any other return value is the final answer and comes back
502 # to the caller untouched (in list context as the list it returned). Anything
503 # it dies with propagates immediately -- a real failure is not retried.
504 #
505 # Every compare-and-swap caller goes through here, so the rules for what counts
506 # as contention live in exactly one place (see _is_contended_ref_error).
507 sub retry_contended {
508 my ( $self, $what, $attempt ) = @_;
509 for my $try ( 1 .. CAS_ATTEMPTS ) {
510 my @answer = $attempt->($try);
511 return wantarray ? @answer : $answer[0] if @answer;
512 _cas_backoff($try);
513 }
514 die "karr: gave up updating $what after " . CAS_ATTEMPTS
515 . " attempts -- too many agents are writing the board at once. "
516 . "Try again.\n";
517 }
518  
519  
520 sub _cas_backoff {
521 my ($try) = @_;
522 my $step = CAS_BACKOFF_STEP * $try;
523 $step = CAS_BACKOFF_CAP if $step > CAS_BACKOFF_CAP;
524 Time::HiRes::sleep( $step + rand CAS_BACKOFF_JITTER );
525 return;
526 }
527  
528 # A ref write fails for two very different reasons once more than one agent is
529 # on the board, and telling them apart is the whole fix for #44 and #46:
530 #
531 # GIT_EMODIFIED the ref moved out from under the OID we guarded against
532 # GIT_ENOTFOUND ...or was deleted, which is the same thing when we expected
533 # a specific old value
534 # GIT_ELOCKED another process holds refs/<name>.lock right now
535 #
536 # All three are transient: read again and retry. Everything else is real.
537 #
538 # GIT_ELOCKED is the one that actually decides whether this works. It is the
539 # common outcome under contention -- libgit2 takes a lock file per ref -- and
540 # Git::Native::Error has no predicate for it, so it has to be compared against
541 # the code. A loop that retries only is_not_matched still loses most writes:
542 # 16 contenders on one counter left 4 processes dead and 4 increments missing.
543 sub _is_contended_ref_error {
544 my ( $err, $guarded ) = @_;
545 return 0 unless blessed($err) && $err->isa('Git::Native::Error');
546 return 1 if $err->code == GIT_ELOCKED;
547 return 1 if $err->is_not_matched;
548 return 1 if $guarded && $err->is_not_found;
549 return 0;
550 }
551  
552 # libgit2 exceptions are Throwable::Error, so stringifying one prints the
553 # message followed by a stack trace full of module paths and line numbers.
554 # That used to reach the user verbatim when an ordinary concurrent ref write
555 # aborted a command mid-body (#46). App::karr::Error::clean_error is the one
556 # reduction to a single line of prose -- this used to carry its own copy of it
557 # -- and the trailing newline stops perl appending " at ... line N." on top.
558 sub _ref_error {
559 my ( $verb, $ref, $err ) = @_;
560 return "karr: could not $verb $ref: " . clean_error($err) . "\n";
561 }
562  
563 # The parentless commit every board ref points at. Built once per write, not
564 # once per attempt: the content does not change while we are losing races for
565 # the ref, and rebuilding it would leave a dangling object behind each time.
566 sub _commit_for_content {
567 my ( $self, $repo, $content ) = @_;
568 my $blob_oid = $repo->blob_create_frombuffer( to_octets($content) );
569 my $tb = $repo->tree_builder;
570 $tb->insert(name => 'data', oid => $blob_oid, mode => 0100644);
571 my $tree_oid = $tb->write;
572  
573 my $sig = $self->_signature;
574 return $repo->commit_create(
575 tree => $tree_oid,
576 parents => [],
577 message => 'karr ref update',
578 author => $sig,
579 committer => $sig,
580 );
581 }
582  
583 # Ref blobs are the octet edge of the board (see App::karr::Encoding): callers
584 # above this line hand over and receive character strings, and
585 # _commit_for_content / read_ref_with_oid are the only two places that convert.
586 #
587 # Unconditional last-writer-wins, which is what most callers want. It still
588 # retries, because losing the race for refs/<name>.lock is not a failed write,
589 # it is a write that has not been attempted yet -- letting that escape killed
590 # 9 of 12 contenders outright (#46).
591 sub write_ref {
592 my ( $self, $ref, $content ) = @_;
593 my $repo = $self->_repo or return;
594 return $self->_write_ref_oid( $ref, $self->_commit_for_content( $repo, $content ) );
595 }
596  
597  
598 # The ref-moving half of write_ref, split out for replace_board_refs, which
599 # has to build every commit in a restore before it moves the first ref.
600 sub _write_ref_oid {
601 my ( $self, $ref, $commit_oid ) = @_;
602 my $repo = $self->_repo or return;
603  
604 return $self->retry_contended( "ref $ref", sub {
605 my $wrote = try {
606 $repo->reference_create( $ref, $commit_oid, force => 1 );
607 1;
608 } catch {
609 my $err = $_;
610 return 0 if _is_contended_ref_error( $err, 0 );
611 die _ref_error( 'write', $ref, $err );
612 };
613 return () unless $wrote;
614 $WRITES++;
615 return 1;
616 } );
617 }
618  
619 # Compare-and-swap sibling of write_ref: the write lands only if the ref still
620 # holds $expected_old, where undef means "the ref must not exist at all".
621 #
622 # Returns 1 when the write landed and 0 when someone else got there first --
623 # the caller is expected to be inside retry_contended, re-read whatever it
624 # decided on, and try again. A real failure dies with a karr-level message.
625 #
626 # $WRITES counts writes that actually landed. SyncGuard reads it to decide
627 # whether local refs still need pushing, so a lost race must not bump it.
628 sub write_ref_cas {
629 my ( $self, $ref, $content, $expected_old ) = @_;
630 my $repo = $self->_repo
631 or die "karr: could not write $ref: "
632 . ( $self->last_error // 'no usable git repository' ) . "\n";
633  
634 return $self->_cas_ref_oid( $ref,
635 $self->_commit_for_content( $repo, $content ), $expected_old );
636 }
637  
638 # The guarded half of write_ref_cas, split out for the one caller that already
639 # has the commit it wants the ref to point at: _adopt_next_id_ref, which moves
640 # the counter onto the remote's own object rather than a copy of its content.
641 # Same answers as write_ref_cas -- 1 landed, 0 someone else got there first,
642 # die on a real failure -- and the same rule about $WRITES: a lost race must
643 # not bump it, because SyncGuard reads it to decide whether to push.
644 sub _cas_ref_oid {
645 my ( $self, $ref, $commit_oid, $expected_old ) = @_;
646 my $repo = $self->_repo
647 or die "karr: could not write $ref: "
648 . ( $self->last_error // 'no usable git repository' ) . "\n";
649  
650 my $wrote = try {
651 $repo->reference_create( $ref, $commit_oid,
652 expected_old => $expected_old );
653 1;
654 } catch {
655 my $err = $_;
656 return 0 if _is_contended_ref_error( $err, defined $expected_old );
657 die _ref_error( 'write', $ref, $err );
658 };
659 return 0 unless $wrote;
660 $WRITES++;
661 return 1;
662 }
663  
664  
665 # Compare-and-swap sibling of delete_ref, and the mirror image of
666 # write_ref_cas: the ref is removed only if it still holds $expected_old.
667 #
668 # libgit2 has two removals and karr only ever reached the unguarded one.
669 # git_reference_remove(repo, name) -- what delete_ref uses -- takes a name and
670 # no expected-old OID, so a delete can never be guarded: whatever the caller
671 # checked may have changed by the time the ref goes. git_reference_delete()
672 # takes a looked-up reference instead and refuses with GIT_EMODIFIED when the
673 # ref on disk no longer matches the one that was looked up, which is exactly
674 # the guarantee the claim guards need (#94).
675 #
676 # Both halves are needed. The explicit OID comparison covers the window
677 # between the caller's read and the lookup here; libgit2's own check covers
678 # the window between that lookup and the removal. Neither alone is a CAS.
679 #
680 # Returns 1 when the delete landed and 0 when the ref had moved or gone -- the
681 # same contract write_ref_cas answers with, so a caller inside retry_contended
682 # re-reads what it decided on and tries again. Contention that has not
683 # committed to an answer yet (another process holding refs/<name>.lock) is
684 # reported as 0 as well, for the same reason: read again and retry. A real
685 # failure dies with a karr-level message.
686 sub delete_ref_cas {
687 my ( $self, $ref, $expected_old ) = @_;
688 defined $expected_old
689 or die "karr: could not delete $ref: no expected revision given\n";
690 my $repo = $self->_repo
691 or die "karr: could not delete $ref: "
692 . ( $self->last_error // 'no usable git repository' ) . "\n";
693  
694 # A miss is "somebody got there first", not an error, and asking first
695 # keeps libgit2 from building a full Throwable stack trace for it.
696 return 0 unless $repo->reference_exists($ref);
697  
698 my $reference = try { $repo->reference($ref) } catch { undef };
699 return 0 unless $reference;
700 my $target = try { $reference->target } catch { undef };
701 return 0 unless $target && $target->hex eq $expected_old;
702  
703 # The OID is already in hand here; see _note_pending_delete.
704 $self->_note_pending_delete( $ref, $expected_old );
705  
706 my $deleted = try {
707 $reference->delete;
708 1;
709 } catch {
710 my $err = $_;
711 return 0 if _is_contended_ref_error( $err, 1 );
712 die _ref_error( 'delete', $ref, $err );
713 };
714 return 0 unless $deleted;
715 $WRITES++;
716 return 1;
717 }
718  
719  
720 # Two answers from one read: the OID the ref points at (undef when the ref is
721 # absent) and the content of that exact commit. Compare-and-swap callers need
722 # both together -- deciding on content fetched independently of the OID would
723 # guard the write against the wrong revision.
724 sub read_ref_with_oid {
725 my ( $self, $ref ) = @_;
726 my $repo = $self->_repo or return ( undef, '' );
727  
728 # Ask whether the ref is there before looking it up. Letting Git::Native
729 # throw for a miss would build a full Throwable stack trace, and this runs
730 # once per task load.
731 return ( undef, '' ) unless $repo->reference_exists($ref);
732 my $oid = try { $repo->reference($ref)->target } catch { undef };
733 return ( undef, '' ) unless $oid;
734  
735 return ( $oid->hex, $self->_content_at_oid( $repo, $oid ) );
736 }
737  
738 # The payload of one karr ref commit, addressed by OID instead of by ref name.
739 # Split out of read_ref_with_oid so reconciliation can read what a mirror
740 # commit says without going through a ref that may have moved since the plan
741 # was made (#172). Takes an OID object or a hex string.
742 sub _content_at_oid {
743 my ( $self, $repo, $oid ) = @_;
744 my $content = try {
745 my $commit = $repo->commit($oid);
746 my $tree = $commit->tree;
747 my $entry = $tree->entry_by_name('data');
748 return '' unless $entry;
749 return $repo->blob( $entry->{oid} )->content;
750 } catch { '' };
751 $content = from_octets($content);
752 # Match historical CLI behaviour: cat-file's trailing newline was chomped.
753 chomp $content if defined $content;
754 return $content;
755 }
756  
757  
758 sub read_ref {
759 my ( $self, $ref ) = @_;
760 return ( $self->read_ref_with_oid($ref) )[1];
761 }
762  
763  
764 sub ref_exists {
765 my ( $self, $ref ) = @_;
766 my $repo = $self->_repo or return 0;
767 return $repo->reference_exists($ref) ? 1 : 0;
768 }
769  
770  
771 # Returns 1 when this call removed the ref and 0 when there was nothing to
772 # remove. It used to swallow the exception and answer 1 regardless (#51), which
773 # made a delete that did nothing look like a delete that worked, and bumped
774 # $WRITES either way. That counter is what SyncGuard reads to decide whether
775 # local refs still need pushing, so it may only ever count writes that landed.
776 #
777 # A delete that was attempted and refused dies, as every other ref mutation in
778 # this class does. It used to answer 0 for that too -- the same 0 as "was never
779 # there" -- and break_lock read that 0 as "gone", so `karr unlock` reported
780 # "Broke lock on task N" over a lock that was still standing (#119). unlock is
781 # the escape hatch for a holder that never came back; a false success there
782 # leaves the card locked for everyone with nobody left to look.
783 #
784 # 0 therefore means "the ref is not on this board", never "we could not tell".
785 # The one seam is an unopenable repository, which is not a refusal to delete
786 # but the whole class degrading to no-ops -- during global destruction _repo is
787 # false by design and nothing native may run or throw (#63).
788 #
789 # Contention retries on the same terms as write_ref: losing the race for
790 # refs/<name>.lock is not a failed delete, it is one that has not been
791 # attempted yet.
792 sub delete_ref {
793 my ( $self, $ref ) = @_;
794 my $repo = $self->_repo or return 0;
795  
796 return $self->retry_contended( "ref $ref", sub {
797 # Asking first keeps "nothing to delete" -- a no-op, not a write --
798 # apart from the failure below, which libgit2 reports the same way.
799 return 0 unless $repo->reference_exists($ref);
800  
801 # Before the ref goes, not after: a crash in between leaves a
802 # tombstone for a ref that is still there, which the push skips,
803 # rather than a deletion no push will ever publish (#178).
804 $self->_note_pending_delete($ref);
805  
806 my $deleted = try {
807 $repo->reference_delete($ref);
808 1;
809 } catch {
810 my $err = $_;
811 return 0 if _is_contended_ref_error( $err, 0 );
812 die _ref_error( 'delete', $ref, $err );
813 };
814 return () unless $deleted;
815 $WRITES++;
816 return 1;
817 } );
818 }
819  
820  
821 # ----- Remote / network ops: native via Git::Native::Remote -----
822  
823 # The push refspec. Forced, because write_ref builds every board commit with
824 # `parents => []`: no board ref update is ever a fast-forward, so a non-forced
825 # refspec can never apply one. push has always been forced; pull was not, and
826 # libgit2 declines a non-ff fetch update without raising an error, so pull
827 # returned success while leaving the ref stale -- and the next push then
828 # force-wrote that stale ref over the other agent's work (#40). Both
829 # directions are forced now; see _fetch_refspec for the pull side.
830 #
831 # The semantics this settles on are last-writer-wins, which is what the
832 # parentless-commit design already implied everywhere else. Doing better
833 # would need compare-and-swap on the ref (git_reference_create_matching,
834 # unbound in Git::Libgit2 -- see ticket #81) plus per-ref rejection reporting
835 # from libgit2's update_tips/push_update_reference callbacks (not installed
836 # by Git::Native -- ticket #80). Neither is reachable from karr today.
837 use constant BOARD_REFSPEC => '+refs/karr/*:refs/karr/*';
838  
839 use constant BOARD_ROOT => 'refs/karr/';
840  
841 # The board's identity (#95): stamped once at board birth, compared on every
842 # pull before any reconciliation -- see _check_board_identity. Declared with
843 # the other namespace constants because use constant is only visible from its
844 # textual point on, and _check_board_identity needs it.
845 use constant BOARD_ID_REF => 'refs/karr/meta/board-id';
846  
847 # The id counter, declared up here with the other namespace constants for the
848 # same reason BOARD_ID_REF is: use constant is only visible from its textual
849 # point on, and the reconciliation below has to name this ref to keep it from
850 # being walked backwards (#172). The allocator that owns it lives further down.
851 use constant NEXT_ID_REF => 'refs/karr/meta/next-id';
852  
853 # Remote-tracking mirror: refs/karr-remote/<remote>/<X> holds the remote's
854 # refs/karr/<X> as of the last successful fetch or push from this clone.
855 #
856 # It exists because "the remote does not have this ref" is two different
857 # situations and the ref alone cannot tell them apart: the remote deleted a
858 # task (prune is right -- #49), or the ref is local work that has not been
859 # pushed yet (prune destroys it). karr promises exactly the latter after a
860 # failed push -- "Local refs are intact. Run 'karr sync' to retry." -- so
861 # pruning on that signal alone broke the promise the sync guard and the END
862 # flush (#37) exist to keep.
863 #
864 # The mirror makes the four cases decidable. See _reconcile_with_mirror.
865 use constant MIRROR_ROOT => 'refs/karr-remote';
866  
867 # Where the local side of a genuine conflict is parked before the remote
868 # version replaces it. Outside refs/karr/, so it never reaches the remote and
869 # never shows up on the board.
870 use constant CONFLICT_ROOT => 'refs/karr-conflict';
871  
872 # Deleted board refs, remembered until a push has told the remote about them.
873 # refs/karr-local/ is the namespace nothing pushes or fetches, so a tombstone
874 # is local bookkeeping the way a pick lock is -- and it points at the commit
875 # the deleted ref pointed at, which keeps that card reachable for a hand
876 # recovery until the deletion is published.
877 #
878 # This is the record a push publishes deletions from, and it exists because
879 # the two obvious alternatives both destroy cards under concurrency (#178):
880 # pruning treats every remote ref the pusher does not have as deleted, and a
881 # mirror-minus-local diff cannot tell a card this clone deleted from one
882 # another process fetched a moment ago and has not adopted into the board yet.
883 # A ref that was deliberately deleted here is the only thing that writes one.
884 use constant TOMBSTONE_ROOT => 'refs/karr-local/deleted';
885  
886 # ----- The fleet-coordination namespace (#190) -----
887 #
888 # karr-foundation's shared half: the chain of planned steps, the run logs, the
889 # question mailbox to come, and the fleet's own design document
890 # (App::karr::Foundation::ChainStore, #189). It is coordination state -- every
891 # machine and every person has to see the same picture -- so it syncs, and it
892 # syncs through the same mirror the board does, for the same reason: without
893 # one, "the remote does not have this ref" cannot be told apart from "this
894 # clone has not pushed it yet", and a namespace whose ref names are minted as
895 # it runs meets both cases constantly.
896 #
897 # What it deliberately does NOT take from the board:
898 #
899 # * No wholesale-wipe guard (#82). An empty chain whose logs have aged out is
900 # the normal end state of a fleet run, not a catastrophe, so a guard here
901 # would fire on the ordinary case -- and the only way past it is a --prune
902 # that arms the board's wipe as well. A guard that has to be typed routinely
903 # is a guard that stops being read.
904 # * No identity of its own (#95). The namespace lives in the hub repository,
905 # whose board is stamped and checked on the same `karr sync`, in front of
906 # this half, against the same remote. A swapped or re-created origin is
907 # refused there before anything here runs. A second stamp would be a second
908 # thing to migrate and would answer no question the first one leaves open.
909 # * No conflict parking (refs/karr-conflict/). The remote still wins where
910 # both sides moved a ref, and the warning still says so, but the displaced
911 # version is not kept: a parked card is something a person reads back, a
912 # parked chain step is a plan nobody re-runs -- the planner writes a new one.
913 #
914 # What it does take, unchanged, is the deletion path (#178): tombstones plus
915 # explicit delete refspecs, never a pruning push. Retention really deletes refs
916 # (App::karr::Foundation::ChainStore/prune_logs), so a namespace with no way to
917 # publish a deletion would re-adopt every pruned run on the next pull, forever;
918 # and a pruning push would take another machine's run log -- just written, never
919 # seen here -- off the remote, which is #178 one namespace over and with more
920 # writers.
921 use constant FOUNDATION_ROOT => 'refs/karr-foundation/';
922  
923 use constant FOUNDATION_REFSPEC =>
924 '+refs/karr-foundation/*:refs/karr-foundation/*';
925  
926 # Both under refs/karr-local/, the namespace nothing pushes or fetches and the
927 # one namespace `karr set-refs` cannot reach (validate_helper_ref). The board's
928 # equivalents sit under refs/karr-remote/ for historical reasons; a mirror and a
929 # tombstone are local bookkeeping, so the new ones are put where that is true by
930 # construction.
931 use constant FOUNDATION_MIRROR_ROOT => 'refs/karr-local/foundation-remote';
932  
933 use constant FOUNDATION_TOMBSTONE_ROOT => 'refs/karr-local/foundation-deleted';
934  
935 # Ref root => tombstone root, for every namespace whose deletions are published
936 # to the remote rather than pruned onto it. Pick locks and the tombstones
937 # themselves are not in here on purpose: they never leave this clone.
938 my @TOMBSTONED = (
939 [ BOARD_ROOT, TOMBSTONE_ROOT ],
940 [ FOUNDATION_ROOT, FOUNDATION_TOMBSTONE_ROOT ],
941 );
942  
943 # What _adopt_next_id_ref answers when the local counter was already the
944 # further one: applied, in the sense that the two sides have converged on it,
945 # but not by taking the remote's version -- which is the difference the
946 # conflict report has to know about.
947 use constant KEPT_LOCAL => 'kept-local';
948  
949 sub _mirror_prefix {
950 my ( $self, $remote, $root ) = @_;
951 return ( $root // MIRROR_ROOT ) . "/$remote/";
952 }
953  
954 # Fetch never writes into the live board any more: the remote state lands in
955 # the mirror, and karr decides per ref what that means. Forced and pruning is
956 # safe here for the same reason -- the mirror is supposed to be an exact copy
957 # of the remote, nothing of ours lives in it.
958 sub _fetch_refspec {
959 my ( $self, $remote ) = @_;
960 return '+refs/karr/*:' . $self->_mirror_prefix($remote) . '*';
961 }
962  
963 sub has_remote {
964 my ( $self, $remote ) = @_;
965 $remote //= 'origin';
966 my $repo = $self->_repo or return 0;
967 return $repo->has_remote($remote);
968 }
969  
970  
971 # The probe behind the automatic fetch in
972 # App::karr::Role::BoardDiscovery/require_local_board (#173): does the remote
973 # hold a board at all? It has to answer that without fetching, because the
974 # caller's other outcome is a refusal, and it has to answer within a bounded
975 # time, because it runs unasked in front of `karr list`.
976 #
977 # Native first, CLI as the fallback -- the same order every other transport
978 # here takes. It was the CLI and only the CLI until #203, on the grounds that
979 # libssh2 retried past libgit2's socket timeout and an ssh:// probe therefore
980 # had no deadline at all (#174, measured); the 1.9.3 floor cpanfile pins closed
981 # that, and the argument went with it. What the CLI is still needed for is the
982 # reason the rest of this class keeps it: libgit2 reads no ~/.ssh/config, so a
983 # Host alias, the IdentityFile, User or Port under it, and a ProxyCommand all
984 # exist only for the CLI. libssh2 takes a remote written as `board:karr.git`
985 # for the literal host `board` and stops at the name lookup (measured), so
986 # there the fallback is not a second opinion but the only route. git config's
987 # own url.*.insteadOf is not part of that list: libgit2 applies the rewrite
988 # itself, as 1.9.3 does here.
989 #
990 # The budget (_probe_timeout: KARR_TRANSPORT_TIMEOUT capped at 10 s) is split
991 # rather than spent twice. The native attempt gets half of it, the CLI gets
992 # whatever is left of the deadline when the native one returns -- so a remote
993 # that is silent rather than absent, the case where both attempts run all the
994 # way to their limit, still costs the cap once. A native attempt that ended the
995 # budget by itself leaves nothing to fall back with, and the probe reports the
996 # deadline instead of forking. With KARR_NO_CLI_FALLBACK there is no second
997 # attempt to hold anything back for, so the native one gets the whole budget:
998 # the switch means "native only" here, the way it does everywhere else in this
999 # class, rather than the "do not ask at all" it used to mean when the CLI was
1000 # the only route.
1001 #
1002 # Nothing here may prompt: this call is not one the user made, so a passphrase
1003 # prompt appearing in the middle of `karr list --json` would be a surprise
1004 # that only the deadline ends. On the CLI side GIT_TERMINAL_PROMPT=0 (set by
1005 # _run_git) covers git's own credential prompts; BatchMode covers ssh's, which
1006 # git never sees. It is appended to the user's own GIT_SSH_COMMAND rather than
1007 # replacing it, so a configured wrapper still runs -- and ssh takes the first
1008 # value it is given for an option, so an explicit BatchMode of theirs still
1009 # wins. The native side runs no ssh binary at all: _default_credentials_cb
1010 # hands libgit2 an agent, a key file with an explicit (empty) passphrase, or
1011 # nothing, and never an interactive credential -- so a passphrase-protected
1012 # key with no agent behind it fails the connection rather than asking anyone.
1013 sub remote_has_board {
1014 my ( $self, $remote ) = @_;
1015 $remote //= 'origin';
1016 return 0 unless $self->has_remote($remote);
1017  
1018 my $budget = _probe_timeout();
1019 my $share = $ENV{KARR_NO_CLI_FALLBACK} ? $budget : $budget / 2;
1020 my $deadline = Time::HiRes::time() + $budget;
1021  
1022 # Set for both attempts: the CLI reaches ssh through this variable, and a
1023 # libgit2 built against the exec ssh transport rather than libssh2 would
1024 # reach it through the same one.
1025 local $ENV{GIT_SSH_COMMAND} =
1026 ( $ENV{GIT_SSH_COMMAND} || 'ssh' ) . ' -o BatchMode=yes';
1027  
1028 my ( $names, $native_why );
1029 if ( my $repo = $self->_repo ) {
1030 # _repo has just applied the transport budget; the probe's is smaller.
1031 _set_native_transport_timeouts($share);
1032 try {
1033 $names = $repo->remote($remote)
1034 ->list_refs( credentials => _default_credentials_cb() );
1035 } catch {
1036 $native_why = clean_error($_);
1037 };
1038 _apply_native_transport_timeouts();
1039 }
1040  
1041 # list_refs answers with the remote's own ref names, HEAD included and no
1042 # refspec mapping applied, so the board is a prefix match. An answer with
1043 # no board ref in it is an answer: the remote has none.
1044 return ( grep { index( $_, BOARD_ROOT ) == 0 } @$names ) ? 1 : 0
1045 if $names;
1046  
1047 my $why = $native_why;
1048 my $left = $deadline - Time::HiRes::time();
1049 if ( $ENV{KARR_NO_CLI_FALLBACK} ) {
1050 # Native only: whatever it said is the whole answer.
1051 }
1052 elsif ( $left <= 0 ) {
1053 $why = "no answer within ${budget}s";
1054 }
1055 else {
1056 my $run = $self->_run_git( { timeout => $left },
1057 'ls-remote', '--quiet', $remote, BOARD_ROOT . '*' );
1058  
1059 if ( $run->{ok} && !$run->{status} ) {
1060 # An answer with no ref in it is an answer: the remote has no board.
1061 return $run->{out} =~ /\S/ ? 1 : 0;
1062 }
1063  
1064 # git's first line is the one that says what went wrong ("ssh: connect
1065 # to host ...", "fatal: '/x' does not appear to be a git repository");
1066 # the rest is the standard advice underneath it, and this becomes one
1067 # line in front of a refusal that has four of its own.
1068 my $detail = $run->{err} // '';
1069 $detail =~ s/\s+\z//;
1070 $detail = ( split /\n/, $detail )[0] // '';
1071 # No git to run leaves the native attempt as the only thing that
1072 # happened, so its reason is carried along. The timeout names the whole
1073 # probe's deadline rather than the slice this attempt was given: what
1074 # the caller waited through is both attempts together.
1075 my $start = "could not run git: $detail"
1076 . ( defined $native_why ? " (native: $native_why)" : '' );
1077 $why =
1078 $run->{failure} eq 'start' ? $start
1079 : $run->{failure} eq 'timeout' ? "no answer within ${budget}s"
1080 : length $detail ? $detail
1081 : "git ls-remote exited " . ( $run->{status} >> 8 );
1082 }
1083  
1084 $self->{_last_error} = $why // 'the remote could not be asked';
1085 return undef;
1086 }
1087  
1088  
1089 # Default credentials callback: SSH-agent → ~/.ssh/id_ed25519 → ~/.ssh/id_rsa
1090 # → default → fail. Matches CLI `git`'s implicit auth chain.
1091 sub _default_credentials_cb {
1092 my @tried;
1093 return sub {
1094 my (%args) = @_;
1095 my $user = $args{username_from_url} || 'git';
1096 my $types = $args{allowed_types} || 0;
1097  
1098 # GIT_CREDENTIAL_SSH_KEY = 1<<1 = 2
1099 if ( $types & 2 ) {
1100 return Git::Native::Credential->ssh_agent( username => $user )
1101 unless $tried[0]++;
1102 for my $k (qw( id_ed25519 id_rsa )) {
1103 my $priv = "$ENV{HOME}/.ssh/$k";
1104 next unless -r $priv;
1105 next if $tried[1]{$k}++;
1106 return Git::Native::Credential->ssh_key(
1107 username => $user,
1108 private_key => $priv,
1109 public_key => "$priv.pub",
1110 passphrase => '',
1111 );
1112 }
1113 }
1114 # GIT_CREDENTIAL_DEFAULT = 1<<3 = 8
1115 if ( ( $types & 8 ) && !$tried[2]++ ) {
1116 return Git::Native::Credential->default;
1117 }
1118 return undef; # PASSTHROUGH — give up
1119 };
1120 }
1121  
1122 sub fetch {
1123 my ( $self, $remote ) = @_;
1124 $remote //= 'origin';
1125 my $repo = $self->_repo or return 0;
1126 return 1 unless $repo->has_remote($remote);
1127 # The Result's ->updated names the refs a fetch actually moved. karr
1128 # deliberately does not use it: reconciliation has to consider the refs the
1129 # fetch did *not* move as well (unpushed local work is exactly that), so it
1130 # reads the ref OIDs itself -- and the CLI transport has no such list to
1131 # hand back, so consuming it would make the two transports differ again,
1132 # which is what #41 was. ->rejected is always empty on fetch.
1133 return $self->_fetch_refspecs( $remote, [] ); # configured refspecs
1134 }
1135  
1136  
1137 # Per-ref rejections from the most recent push, as
1138 # [ { ref => $name, reason => $text }, ... ]. Empty when the last push
1139 # succeeded, and empty when it failed as a whole (no connection, killed
1140 # transport) rather than ref by ref -- a rejection is the server's final
1141 # answer, so App::karr::Role::SyncLifecycle uses this to stop retrying it.
1142 sub push_rejections {
1143 my ($self) = @_;
1144 return $self->{_push_rejections} || [];
1145 }
1146  
1147  
1148 # Reasons the receiving side gives for "another push got to this ref first",
1149 # as opposed to "I refuse this ref". The wording is all karr gets, so both
1150 # transports' phrasings are named here:
1151 #
1152 # a reference with that name already exists
1153 # libgit2's local transport -- a bare repo reached by a path or by
1154 # file://, which is what the tests and the reproducers use. It looks the
1155 # destination ref up, finds nothing, and creates it *without* force, so
1156 # a ref another push created in between fails the create. karr never
1157 # asks for a forceless create: the board refspec is +refs/karr/*.
1158 #
1159 # failed to update ref
1160 # git-receive-pack, which is what every real ssh/https/git:// remote
1161 # runs, reported over either transport (libgit2's smart protocol, or
1162 # `git push --porcelain`). It is receive-pack's status for a ref
1163 # transaction that would not commit: the old value the pusher was
1164 # advertised no longer matches, or the ref it wanted to create now
1165 # exists. The detail goes to the sideband as "cannot lock ref 'X':
1166 # reference already exists" and never into the status line, so this
1167 # bare wording is what arrives.
1168 #
1169 # cannot lock ref / failed to lock
1170 # the same thing, where the detail does survive.
1171 #
1172 # This race is not a quirk of the local transport (#181): 8 parallel creates
1173 # in one clone left 3 of 10 runs with a failed create against a path remote,
1174 # and 4 to 5 of 8 creates failing in *every* run against a `git daemon` --
1175 # a real receive-pack, whose ref transaction is atomic, so one contended ref
1176 # takes the whole push down with it.
1177 #
1178 # Deliberately an allowlist. Everything else -- "pre-receive hook declined",
1179 # "protected ref", "non-fast-forward" -- stays what #84 made it: the server's
1180 # final answer, not retried. "failed to update ref" also covers ref-store
1181 # failures that will never come right (a directory/file conflict, a full
1182 # disk); those cost the caller its remaining attempts and then fail with the
1183 # ordinary "push failed" verdict, which is the cheaper way to be wrong.
1184 sub _is_contended_push_reason {
1185 my ($reason) = @_;
1186 return 0 unless defined $reason && length $reason;
1187 return 1 if $reason =~ /reference with that name already exists/i;
1188 return 1 if $reason =~ /reference already exists/i;
1189 return 1 if $reason =~ /failed to update ref/i;
1190 return 1 if $reason =~ /cannot lock ref/i;
1191 return 1 if $reason =~ /failed to lock/i;
1192 return 0;
1193 }
1194  
1195 sub push_contention {
1196 my ($self) = @_;
1197 my $rejected = $self->push_rejections;
1198 return 0 unless @$rejected;
1199 for my $entry (@$rejected) {
1200 return 0 unless _is_contended_push_reason( $entry->{reason} );
1201 }
1202 return 1;
1203 }
1204  
1205  
1206 # libgit2 returns 0 from git_remote_push even when the server refused every
1207 # single ref -- a pre-receive hook, a protected ref, a non-ff on a non-forced
1208 # refspec. The per-ref status only exists in the Result Git::Native 0.004
1209 # hands back, and karr threw that away, so a push that landed nothing was
1210 # reported as a completed sync and the board diverged in silence (#84).
1211 #
1212 # A rejection is not a transport failure: the connection worked and the far
1213 # side said no. So this does not fall through to the CLI fallback -- that
1214 # would just collect the same refusal a second time, and hide the reason
1215 # behind a generic exit code.
1216 sub _accept_push_result {
1217 my ( $self, $remote, $result ) = @_;
1218 return 1 unless $result; # CLI fallback ran instead
1219 my $rejected = $result->rejected;
1220 return 1 unless $rejected && @$rejected;
1221 $self->{_push_rejections} = $rejected;
1222 $self->{_last_error} =
1223 _push_rejection_error( $remote, $rejected, scalar @{ $result->updated } );
1224 return 0;
1225 }
1226  
1227 # One line per refused ref, with the reason the far side gave, because "the
1228 # push failed" without naming the ref is not actionable on a board where one
1229 # protected ref among fifty is the normal case.
1230 sub _push_rejection_error {
1231 my ( $remote, $rejected, $accepted ) = @_;
1232 my $total = @$rejected + ( $accepted // 0 );
1233 my $head = @$rejected == $total
1234 ? sprintf( "the remote '%s' rejected all %d ref%s",
1235 $remote, $total, $total == 1 ? '' : 's' )
1236 : sprintf( "the remote '%s' rejected %d of %d refs",
1237 $remote, scalar @$rejected, $total );
1238 return join "\n", "$head:", map {
1239 ' '
1240 . $_->{ref} . ': '
1241 . ( defined $_->{reason} && length $_->{reason}
1242 ? $_->{reason} : 'no reason given' )
1243 } @$rejected;
1244 }
1245  
1246 # libgit2 resolves a remote's push URL when it looks the remote up -- an
1247 # explicit remote.<name>.pushurl, or url.<base>.pushInsteadOf applied to the
1248 # fetch URL when there is none -- and leaves it NULL when neither is
1249 # configured, which is every ordinary board. Git::Native exposes the fetch URL
1250 # and not this one, and Git::Libgit2::FFI binds no git_remote_pushurl, so it is
1251 # reached here through their shared FFI instance. Deliberately a function
1252 # object rather than an attached sub, and never installed into their namespace:
1253 # a binding added upstream later must not collide with this one. Undef when the
1254 # symbol cannot be reached at all, which reads the same as "no push URL" and
1255 # leaves the push exactly as it was before this check existed.
1256 my $REMOTE_PUSHURL_FN;
1257  
1258 sub _remote_pushurl {
1259 my ($remote_obj) = @_;
1260 unless ( defined $REMOTE_PUSHURL_FN ) {
1261 $REMOTE_PUSHURL_FN = try {
1262 Git::Libgit2::FFI::ffi->function(
1263 git_remote_pushurl => ['opaque'] => 'string' );
1264 } catch { 0 };
1265 }
1266 return undef unless $REMOTE_PUSHURL_FN;
1267 my $url = try { $REMOTE_PUSHURL_FN->call( $remote_obj->_handle ) }
1268 catch { undef };
1269 return defined $url && length $url ? from_octets($url) : undef;
1270 }
1271  
1272 # Which transport libgit2 picks for a URL, reduced to the one distinction that
1273 # matters here: its local transport, or a real one. Same reading git does -- an
1274 # explicit scheme decides and file:// is the local one, otherwise a colon
1275 # before the first slash makes it an scp-style ssh remote, and what is left is
1276 # a path.
1277 sub _is_local_url {
1278 my ($url) = @_;
1279 return 1 if $url =~ m{\Afile://}i;
1280 return 0 if $url =~ m{\A[A-Za-z][A-Za-z0-9+.\-]*://};
1281 return 0 if $url =~ m{\A[^/]*:};
1282 return 1;
1283 }
1284  
1285 # The one shape where the native push connects to the right repository and
1286 # writes to the wrong one (#208).
1287 #
1288 # libgit2's local transport pushes by opening remote->url -- the *fetch* URL --
1289 # rather than the URL it was handed for the push. So a remote whose push URL
1290 # resolves to a local path different from its fetch URL connects to the push
1291 # URL, and then puts the objects and the refs in the fetch URL's repository and
1292 # reports success. Measured on the 1.9.3 Alien::Libgit2 carries, in both shapes
1293 # that produce a distinct push URL -- remote.<name>.pushurl and
1294 # url.<base>.pushInsteadOf -- by reading back which of two bare repositories
1295 # had actually received refs/karr/*. That is a published board that never
1296 # reached the remote, with nothing failing for the CLI fallback to catch, so
1297 # the fallback is put in front of the push instead: the git CLI lands at the
1298 # push URL in every one of these cases, which is where this remote's board
1299 # belongs.
1300 #
1301 # Narrow on purpose. An ordinary board has no push URL at all, so this is one
1302 # NULL check and no string work; a push URL identical to the fetch URL is the
1303 # same repository either way; and where the push URL is a real transport
1304 # libgit2 is correct, which is where all the ssh and https boards are. What is
1305 # left over is the shape above -- and a fetch URL that is not local, where the
1306 # native push would fail rather than misdirect (it opens a URL that is no path)
1307 # and the CLI is the route regardless.
1308 #
1309 # Returns the reason as a message, or the empty list when the push may run
1310 # natively. The message is what App::karr::Git/last_error carries when
1311 # KARR_NO_CLI_FALLBACK leaves no route to take instead: a named refusal, rather
1312 # than a success that went somewhere else.
1313 sub _misdirected_local_push {
1314 my ($remote_obj) = @_;
1315 my $push = _remote_pushurl($remote_obj) or return ();
1316 my $url = from_octets( $remote_obj->url // '' );
1317 return () if $push eq $url;
1318 return () unless _is_local_url($push);
1319 return "the remote's push URL ($push) is a local path different from its "
1320 . "fetch URL ($url), and libgit2's local transport writes to the fetch "
1321 . "URL regardless (#208) -- the git CLI is the only route that lands "
1322 . "where this remote points";
1323 }
1324  
1325 # Send @$refspecs and report the outcome the way every caller here needs it:
1326 # native transport first, CLI fallback on a transport failure, and a per-ref
1327 # rejection turned into a false return with last_error and push_rejections set.
1328 # The three public pushes -- the board's, a single helper ref's and the fleet
1329 # namespace's -- differ in what they send and in what they do afterwards, never
1330 # in this, so it is written once.
1331 sub _push_refspecs {
1332 my ( $self, $remote, $refspecs ) = @_;
1333 my $repo = $self->_repo or return 0;
1334 $self->{_push_rejections} = [];
1335  
1336 my $result;
1337 my $ok = try {
1338 my $r = $repo->remote($remote);
1339 if ( my $why = _misdirected_local_push($r) ) {
1340 $self->{_last_error} = $why;
1341 return $self->_cli_transport( 'push', $remote, $refspecs );
1342 }
1343 $result = $r->push(
1344 refspecs => $refspecs,
1345 credentials => _default_credentials_cb(),
1346 );
1347 1;
1348 } catch {
1349 $self->{_last_error} = "$_";
1350 $self->_cli_transport( 'push', $remote, $refspecs );
1351 };
1352 return 0 unless $ok;
1353 return $self->_accept_push_result( $remote, $result ) ? 1 : 0;
1354 }
1355  
1356 # The fetch half of the same: native first, CLI fallback, no reconciliation.
1357 # An empty @$refspecs means the remote's configured ones.
1358 sub _fetch_refspecs {
1359 my ( $self, $remote, $refspecs, %opt ) = @_;
1360 my $repo = $self->_repo or return 0;
1361 return try {
1362 my $r = $repo->remote($remote);
1363 $r->fetch(
1364 refspecs => $refspecs,
1365 credentials => _default_credentials_cb(),
1366 ( $opt{prune} ? ( prune => 1 ) : () ),
1367 );
1368 1;
1369 } catch {
1370 $self->{_last_error} = "$_";
1371 $self->_cli_transport( 'fetch', $remote, $refspecs, %opt );
1372 };
1373 }
1374  
1375 sub push {
1376 my ( $self, $remote, $refspec ) = @_;
1377 $remote //= 'origin';
1378 my $repo = $self->_repo or return 0;
1379 $refspec //= BOARD_REFSPEC;
1380 my $board = $refspec eq BOARD_REFSPEC;
1381  
1382 # No remote is no debt. A tombstone is the record of a deletion this clone
1383 # owes the remote (TOMBSTONE_ROOT), and _clear_pending_deletes only ever
1384 # ran after a push that landed -- so a repository with no remote, where
1385 # this returns before anything else happens, kept one ref per deleted card
1386 # forever, each of them holding the deleted commit reachable (#197).
1387 #
1388 # Settled here rather than given a retention age, because a tombstone is
1389 # push bookkeeping: keeping the card recoverable is a side effect of
1390 # pointing it at the deleted commit, not its job, nothing reads one back,
1391 # and an age limit would need a deletion time this ref does not carry (its
1392 # commit's date is when the card was last written) plus a policy to
1393 # configure. The unpleasant case decides it: with the record kept, adding
1394 # a remote later makes the first push publish every deletion ever made
1395 # here, and a push checks no board identity -- #95 guards the pull -- so a
1396 # board that happens to have cards at those paths loses them.
1397 #
1398 # has_pending_deletes, the auto-fetch guard (#173), still reads correctly:
1399 # it is only consulted after has_remote, and without a remote there is
1400 # nothing to fetch back.
1401 unless ( $repo->has_remote($remote) ) {
1402 $self->_settle_local_deletes(BOARD_ROOT) if $board;
1403 return 1;
1404 }
1405  
1406 # A board push publishes exactly two things: the local refs as they stand
1407 # here, and the deletions this clone recorded. It used to publish a third
1408 # -- "and nothing else exists", via prune -- which is a claim no clone is
1409 # in a position to make: a card another clone created a second ago is one
1410 # this one has never seen, and pruning deleted it off the remote, after
1411 # which _mirror_local_state made the mirror agree and the next pull read
1412 # it as a deletion the remote had made and removed the card locally too.
1413 # Eight parallel creates in one clone lost a whole card that way, and one
1414 # `karr sync --push` from a clone that had not pulled did it on its own
1415 # (#178).
1416 #
1417 # The snapshot is read before the push rather than after: the refspec is
1418 # expanded inside the push, so a ref written in between is published
1419 # without being in the snapshot -- which leaves the mirror lagging the
1420 # remote, the direction that converges harmlessly (see
1421 # _mirror_local_state). Reading it afterwards is the direction that
1422 # loses cards: the mirror would claim refs the push never carried.
1423 my ( $local, $tombstones, @deletes );
1424 if ($board) {
1425 $local = $self->ref_oids(BOARD_ROOT) || {};
1426 $tombstones = $self->_pending_deletes;
1427 # A tombstone whose ref is back on the board is stale, not a
1428 # deletion: `karr restore` deletes refs/karr/meta/board-id on its way
1429 # through and writes it straight back (#95), and publishing that
1430 # tombstone would take the board's identity off the remote.
1431 @deletes = grep { !exists $local->{$_} } sort keys %$tombstones;
1432 }
1433 my @refspecs = ( $refspec, map { ":$_" } @deletes );
1434  
1435 return 0 unless $self->_push_refspecs( $remote, \@refspecs );
1436  
1437 # A push that went through put the local refs on the remote and took the
1438 # published deletions off it, so the mirror follows both. Without this
1439 # every ref this clone ever pushed would still look "changed locally" on
1440 # the next pull, and the other agent's perfectly ordinary update would be
1441 # reported as a conflict.
1442 if ($board) {
1443 $self->_mirror_local_state( $remote, $local, \@deletes );
1444 $self->_clear_pending_deletes( $tombstones, \@deletes );
1445 }
1446 return 1;
1447 }
1448  
1449  
1450 # %opt: accept_wipe => bool, the caller's answer to _refuse_wholesale_wipe;
1451 # accept_foreign => bool, its answer to _check_board_identity. Only
1452 # `karr sync --prune` sets the first and `karr sync --accept-foreign-board`
1453 # the second; every other pull refuses to reconcile the whole board out of
1454 # existence, or onto a different board (#82, #95).
1455 sub pull {
1456 my ( $self, $remote, %opt ) = @_;
1457 $remote //= 'origin';
1458 my $repo = $self->_repo or return 0;
1459 return 1 unless $repo->has_remote($remote);
1460  
1461 my $refspec = $self->_fetch_refspec($remote);
1462  
1463 # The mirror as it stands now is the remote state at the last sync; the
1464 # fetch is about to overwrite it with the current one. Both are needed to
1465 # tell the four cases apart, so snapshot it first.
1466 my $tracked = $self->ref_oids( $self->_mirror_prefix($remote) ) || {};
1467  
1468 return 0 unless $self->_fetch_refspecs( $remote, [$refspec], prune => 1 );
1469  
1470 $self->_check_board_identity( $remote, $tracked, $opt{accept_foreign} );
1471 $self->_reconcile_with_mirror( $remote, $tracked, $opt{accept_wipe} );
1472 return 1;
1473 }
1474  
1475  
1476 # The identity half of the pull guards (#95), run after the fetch and before
1477 # any reconciliation. The wipe guard cannot see this case at all: a remote
1478 # swapped for a DIFFERENT non-empty board -- a stale clone, a re-initialised
1479 # origin, a typo in the remote URL -- has plenty of refs, just not this
1480 # board's, and reconciliation used to converge the local board onto it in one
1481 # step, silently and totally. The four shapes a pull can meet:
1482 #
1483 # both sides stamped, ids differ the remote was swapped -> refuse, mirror
1484 # rolled back, unless the caller opted in
1485 # with accept_foreign
1486 # remote stamped, local not a clone's first pull -> reconciliation
1487 # adopts the id ref along with the board
1488 # local stamped, remote not a pre-change remote (or one an old karr
1489 # pruned the stamp off with its forced,
1490 # pruning push) -> keep the local id; the
1491 # next push re-arms the remote
1492 # neither stamped a pre-change board -> stamp it now, and
1493 # the ordinary push path arms the remote
1494 #
1495 # An absent id is never a refusal by itself: an empty remote remains the wipe
1496 # guard's case, and a non-empty one a board from before identities existed.
1497 sub _check_board_identity {
1498 my ( $self, $remote, $tracked, $accept_foreign ) = @_;
1499 my $prefix = $self->_mirror_prefix($remote);
1500 my $remote_id = $self->_read_id_ref( $prefix . 'meta/board-id' );
1501 my $local_id = $self->read_board_id_ref;
1502  
1503 if ( defined $remote_id && defined $local_id && $remote_id ne $local_id ) {
1504 return if $accept_foreign;
1505 # Same rule as the wipe guard: put the mirror back first, or the
1506 # refusal is a one-shot -- the next pull would read the foreign board
1507 # as already-reconciled state and walk straight through.
1508 my @stale = $self->_restore_mirror( $remote, $tracked );
1509 die "karr: refusing to sync: the remote '$remote' is a different board.\n"
1510 . "This clone has been syncing with board $local_id, but the remote "
1511 . "now presents board $remote_id.\n"
1512 . "That is what a re-initialised origin, an edited remote URL, or a "
1513 . "stale clone pointed at the wrong repository looks like.\n"
1514 . "Check the remote first (git remote -v). Then either republish this "
1515 . "board over it with 'karr sync --push', or -- if the remote's board "
1516 . "really is the one you want now -- adopt it with 'karr sync "
1517 . "--accept-foreign-board'.\n"
1518 . $self->_mirror_rollback_note( $remote, \@stale );
1519 }
1520  
1521 if ( defined $local_id && !defined $remote_id ) {
1522 # A pre-change karr's forced, pruning push drops the stamp off the
1523 # remote while the rest of the board stays. That remote is still this
1524 # board, so keep the identity continuous: point the mirror's stamp
1525 # slot back at the local stamp, or reconciliation would read the
1526 # missing ref as "the remote deleted the id" and strip it here too.
1527 # Only while the remote still IS a board -- an empty one is the wipe
1528 # guard's case, and the stamp must not count as a survivor there.
1529 my $remote_now = $self->ref_oids($prefix) || {};
1530 if ( %$remote_now ) {
1531 my ( $oid ) = $self->read_ref_with_oid(BOARD_ID_REF);
1532 my $slot = $prefix . 'meta/board-id';
1533 # Unchecked, this was the same defect as #154 one ref over: the
1534 # mirror would keep saying the remote has no stamp, reconciliation
1535 # would read that as "the remote deleted the id" and strip it here
1536 # too, and the next clone to pull would meet a board that had lost
1537 # its identity. Stopping leaves the local stamp untouched and the
1538 # next push re-arms the remote, which is the outcome this branch is
1539 # for anyway.
1540 if ( defined $oid && !$self->_write_ref_untracked( $slot, $oid ) ) {
1541 die "karr: could not update the tracking mirror for '$remote' "
1542 . "($slot).\n"
1543 . "Another karr process is writing it, or a .lock file under "
1544 . ".git/refs/ was left behind by one that was killed.\n"
1545 . "The pull stopped before reconciling: going on would strip "
1546 . "this board's identity stamp. Clear the lock and run 'karr "
1547 . "sync' again.\n";
1548 }
1549 }
1550 return;
1551 }
1552  
1553 if ( !defined $remote_id && !defined $local_id ) {
1554 # Only when there is a board to name at all: an empty clone pulling
1555 # an empty remote gets no stray meta ref.
1556 my $remote_now = $self->ref_oids($prefix) || {};
1557 my $local = $self->ref_oids(BOARD_ROOT) || {};
1558 $self->ensure_board_id_ref if %$remote_now || %$local;
1559 }
1560 return;
1561 }
1562  
1563 # Bring the local board in line with the remote, one ref at a time, using
1564 # L = local, T = the mirror before this fetch (the remote at the last sync)
1565 # and R = the mirror after it (the remote now).
1566 #
1567 # L == T, R exists the local ref carries nothing the remote has not
1568 # seen -> take R. This is the #40 fix: without it the
1569 # stale local ref survived the pull and the next push
1570 # force-wrote it over the other agent's work.
1571 # L == T, R gone the remote deleted it -> delete it here too (#49).
1572 # L != T, R == T only this clone moved: work that was written but
1573 # never pushed -> keep it exactly as it is. Covers a
1574 # local deletion too, which must stay deleted rather
1575 # than being restored from a remote that has not been
1576 # told about it yet.
1577 # L != T, R != T both sides moved. Last-writer-wins still applies
1578 # and R takes the slot -- including when R is a
1579 # deletion -- but the local version is parked and the
1580 # user is told, instead of it disappearing without a
1581 # word.
1582 #
1583 # A clone that predates the mirror has T empty everywhere, so every ref reads
1584 # as "changed locally". That degrades to the right outcome: refs that already
1585 # match the remote are left alone (the normal case for a clone that pushes at
1586 # the end of every command), a remote-only update is still adopted -- with one
1587 # spurious conflict report -- and nothing local is dropped. From the next pull
1588 # on the mirror is populated and the answers are exact.
1589 # The decision is taken for every ref before any of it is applied, because the
1590 # guard against a wholesale wipe (#82) is a property of the plan as a whole,
1591 # not of a single ref, and it has to fire before the first deletion lands.
1592 sub _reconcile_with_mirror {
1593 my ( $self, $remote, $tracked, $accept_wipe ) = @_;
1594 return unless $self->_repo;
1595  
1596 my $prefix = $self->_mirror_prefix($remote);
1597 my ( $plan, $survivors, $deletes ) =
1598 $self->_mirror_plan( BOARD_ROOT, $prefix, $tracked );
1599 my @plan = @$plan;
1600  
1601 $self->_refuse_wholesale_wipe( $remote, $tracked, $deletes )
1602 if $deletes && !$survivors && !$accept_wipe;
1603  
1604 my ( @conflicts, @unapplied, @stale );
1605 for my $step (@plan) {
1606 my ( $ref, $oid, $displaced, $conflict ) = @$step;
1607 # Nothing to park when the local side of a conflict is a deletion:
1608 # there is no commit left to keep reachable, but the clone that made
1609 # that deletion is still told the remote undid it. A park that did not
1610 # land counts as the step failing: half-applying it would drop the
1611 # local commit with nowhere to point the report at.
1612 my $parked = defined $displaced
1613 ? $self->_park_conflicting_local( $remote, $ref, $displaced )
1614 : 1;
1615  
1616 my $applied = $parked && $self->_adopt_remote_ref( $ref, $oid );
1617 if ($applied) {
1618 # KEPT_LOCAL is the counter declining the remote's older value
1619 # (see _adopt_next_id_ref). It is not a conflict to report: the
1620 # warning says the remote version is now in place and the local
1621 # one was parked, and for this ref neither is true.
1622 CORE::push @conflicts, $ref
1623 if $conflict && $applied ne KEPT_LOCAL;
1624 next;
1625 }
1626  
1627 # The plan was right and the apply failed. Both halves matter: the
1628 # mirror goes back to the value this ref had before the fetch, and the
1629 # pull stops. See _rollback_mirror_ref for what the first one prevents.
1630 CORE::push @unapplied, $ref;
1631 CORE::push @stale, $self->_rollback_mirror_ref( $prefix, $tracked, $ref );
1632 }
1633  
1634 # The conflicts that did land are real and still worth reporting, even on
1635 # the way to the failure below.
1636 $self->_warn_conflicts( $remote, \@conflicts ) if @conflicts;
1637 die $self->_unapplied_refs_error( $remote, \@unapplied, \@stale )
1638 if @unapplied;
1639 return;
1640 }
1641  
1642 # The four cases above, decided for every ref of one namespace and for none of
1643 # them applied. $root is the live namespace (refs/karr/ or refs/karr-foundation/),
1644 # $prefix its mirror for this remote, %$tracked the mirror as it stood before
1645 # the fetch.
1646 #
1647 # Returns ( \@plan, $survivors, $deletes ), where a plan entry is
1648 # [ ref, remote oid (undef = delete), local oid displaced (undef = none),
1649 # is a conflict ]. The two counts are the wipe guard's evidence (#82); a caller
1650 # with no wipe guard -- the fleet namespace, see FOUNDATION_ROOT -- ignores them.
1651 #
1652 # Shared rather than written once per namespace: the four cases are the whole
1653 # reasoning of this file, and two copies of them would diverge on the first
1654 # ticket that touches one.
1655 sub _mirror_plan {
1656 my ( $self, $root, $prefix, $tracked ) = @_;
1657  
1658 my $remote_now = $self->ref_oids($prefix) || {};
1659 my $local = $self->ref_oids($root) || {};
1660  
1661 my %names = map { $_ => 1 } keys %$local;
1662 for my $mirror ( keys %$remote_now, keys %$tracked ) {
1663 $names{ $root . substr( $mirror, length $prefix ) } = 1;
1664 }
1665  
1666 my @plan;
1667 my ( $survivors, $deletes ) = ( 0, 0 );
1668 for my $ref ( sort keys %names ) {
1669 my $mirror = $prefix . substr( $ref, length $root );
1670 my ( $l, $r, $t ) =
1671 ( $local->{$ref}, $remote_now->{$mirror}, $tracked->{$mirror} );
1672  
1673 if ( _same_oid( $l, $r ) ) { # already converged
1674 $survivors++ if defined $l;
1675 next;
1676 }
1677  
1678 if ( _same_oid( $l, $t ) ) {
1679 CORE::push @plan, [ $ref, $r, undef, 0 ];
1680 # What the wipe guard counts, and why only here: this branch is
1681 # the deletion the clone cannot see coming and cannot undo -- it
1682 # holds nothing of its own for this ref, so nothing is parked and
1683 # nothing is warned about. Those are the ones that add up to a
1684 # board disappearing without a word (#82). The case-4 branch below
1685 # also deletes, but it parks the local version and says so, so it
1686 # is not a silent loss and does not count. A ref the remote never
1687 # had (both undef) is not a loss either.
1688 if ( defined $r ) { $survivors++ }
1689 elsif ( defined $l ) { $deletes++ }
1690 }
1691 elsif ( _same_oid( $r, $t ) ) { # unpushed local work: keep it
1692 $survivors++ if defined $l;
1693 }
1694 else {
1695 CORE::push @plan, [ $ref, $r, $l, 1 ];
1696 $survivors++ if defined $r;
1697 }
1698 }
1699 return ( \@plan, $survivors, $deletes );
1700 }
1701  
1702 # The invariant the whole reconciliation rests on: the mirror may only claim
1703 # what is actually in place here.
1704 #
1705 # A ref that could not be applied has to leave the mirror at the value it had
1706 # before this fetch. Left advanced, the next pull reads the remote's version as
1707 # state this clone has already reconciled against, so the stale local ref comes
1708 # out as L != T, R == T -- "unpushed local work: keep it" -- and the forced,
1709 # pruning push writes it over the remote's newer card, in every clone, at exit
1710 # 0 (#154). Rolled back, the same pull sees the case it saw this time and
1711 # applies it. Returns the mirror ref name when even the rollback did not land.
1712 sub _rollback_mirror_ref {
1713 my ( $self, $prefix, $tracked, $ref, $root ) = @_;
1714 my $name = $prefix . substr( $ref, length( $root // BOARD_ROOT ) );
1715 my $ok = exists $tracked->{$name}
1716 ? $self->_write_ref_untracked( $name, $tracked->{$name} )
1717 : $self->_delete_ref_untracked($name);
1718 return $ok ? () : $name;
1719 }
1720  
1721 # A pull that decided what the remote says and could not put some of it in
1722 # place. Reported as an exception rather than a false return, because the
1723 # caller's next step is the push, and pushing after a partial pull is the
1724 # destructive step: this clone would force-write the older version it still
1725 # holds over the newer one it just failed to take (#154).
1726 sub _unapplied_refs_error {
1727 my ( $self, $remote, $refs, $stale ) = @_;
1728 my $names = join ', ', @$refs;
1729 my $those = @$refs == 1 ? 'that ref' : 'those refs';
1730 return "karr: could not apply the remote's version of $names.\n"
1731 . "Another karr process is writing $those, or a .lock file under "
1732 . ".git/refs/ was left behind by one that was killed.\n"
1733 . "The pull stopped there and nothing was pushed: this clone still "
1734 . "holds the older version of $those, and pushing it would overwrite "
1735 . "the remote's.\n"
1736 . "Clear the lock (or wait for the other process) and run 'karr sync' "
1737 . "again.\n"
1738 . $self->_mirror_rollback_note( $remote, $stale );
1739 }
1740  
1741 # Said out loud because nothing here can fix it: a mirror that could not be put
1742 # back leaves the refs it names claiming a remote state this clone never
1743 # reconciled against, which is exactly the shape that turns a stopped pull into
1744 # a lost card on the next one. The refusals below share it for the same reason
1745 # -- their rollback is what keeps them from being one-shots.
1746 sub _mirror_rollback_note {
1747 my ( $self, $remote, $stale ) = @_;
1748 return '' unless $stale && @$stale;
1749 return "\nkarr: the tracking mirror for '$remote' could not be put back: "
1750 . join( ', ', sort @$stale ) . ".\n"
1751 . "Until it is, this clone believes it has already seen the remote's "
1752 . "current state for those refs. Do not run a writing command against "
1753 . "it before a 'karr sync' completes.\n";
1754 }
1755  
1756 # Refuse to reconcile a board out of existence.
1757 #
1758 # "The remote had these refs at the last sync and does not have them now" is a
1759 # well-founded observation once the mirror is in place, and acting on it is
1760 # what makes a `karr delete` propagate and a `karr destroy` take effect across
1761 # clones. It is also indistinguishable from a remote that is empty for the
1762 # wrong reason -- origin re-created or re-initialised, the remote URL edited to
1763 # point somewhere else, a hosting-side restore that rolled the namespace back
1764 # -- and in those, a routine writing command reconciles the whole board down to
1765 # nothing, in one step and without a word (#82).
1766 #
1767 # Nothing in the refs can tell those apart, so the wholesale case, and only
1768 # that one, asks a human. A pull that would leave at least one board ref
1769 # standing is ordinary reconciliation and still runs unattended.
1770 #
1771 # The mirror is rolled back to what it was before the fetch first. Leaving it
1772 # emptied would make the very next pull read every local ref as unpushed work
1773 # (L != T, R == T), keep the board, and then push it back at whatever the
1774 # remote has become -- turning one refusal into a silent resurrection, and
1775 # making the refusal a one-shot that never fires again.
1776 sub _refuse_wholesale_wipe {
1777 my ( $self, $remote, $tracked, $deletes ) = @_;
1778 my @stale = $self->_restore_mirror( $remote, $tracked );
1779 die "karr: refusing to sync: this would delete the whole board.\n"
1780 . "The remote '$remote' no longer has any of the $deletes board ref"
1781 . ( $deletes == 1 ? '' : 's' ) . " it had at the last sync.\n"
1782 . "That is what 'karr destroy' on another clone looks like -- and also "
1783 . "what a re-created origin, an edited remote URL, or a rolled-back "
1784 . "hosting-side restore look like.\n"
1785 . "Check the remote first (git remote -v). Then either republish this "
1786 . "board with 'karr sync --push', or accept the deletion with "
1787 . "'karr sync --prune'.\n"
1788 . $self->_mirror_rollback_note( $remote, \@stale );
1789 }
1790  
1791 # Put the mirror back the way the caller found it. Safe to do with bare OIDs:
1792 # the refs/karr/* refs still point at those commits (that is what makes this a
1793 # wholesale wipe), so nothing has become unreachable in between.
1794 #
1795 # Returns the mirror refs it could not put back, which both callers report:
1796 # this rollback is the only thing keeping their refusal from being a one-shot,
1797 # so a half-done one is not something to discover on the next pull (#154).
1798 sub _restore_mirror {
1799 my ( $self, $remote, $tracked ) = @_;
1800 my $prefix = $self->_mirror_prefix($remote);
1801 my $now = $self->ref_oids($prefix) || {};
1802  
1803 my @stale;
1804 for my $name ( keys %$tracked ) {
1805 next if _same_oid( $now->{$name}, $tracked->{$name} );
1806 CORE::push @stale, $name
1807 unless $self->_write_ref_untracked( $name, $tracked->{$name} );
1808 }
1809 for my $name ( keys %$now ) {
1810 next if exists $tracked->{$name};
1811 CORE::push @stale, $name unless $self->_delete_ref_untracked($name);
1812 }
1813 return @stale;
1814 }
1815  
1816 # Put the remote's answer for one ref in place. An undefined OID is the
1817 # remote's answer too: it means the ref is gone there. Returns whether the
1818 # answer is now in place -- the caller has to act on that, see #154.
1819 sub _adopt_remote_ref {
1820 my ( $self, $ref, $oid ) = @_;
1821 return $self->_adopt_next_id_ref($oid)
1822 if $ref eq NEXT_ID_REF && defined $oid;
1823 return defined $oid
1824 ? $self->_write_ref_untracked( $ref, $oid )
1825 : $self->_delete_ref_untracked($ref);
1826 }
1827  
1828 # The id counter is the one board ref whose value may only ever move forward,
1829 # so it is merged rather than adopted: the remote's value lands only when it
1830 # is ahead of the local one.
1831 #
1832 # Plain last-writer-wins walked it backwards two different ways, and either
1833 # one hands a live id out a second time. Reconciliation decides from a
1834 # snapshot of the local refs and applies that decision later with a forced
1835 # write, so a `karr create` that allocated in between is undone; and the
1836 # remote can legitimately be behind, because every push force-writes the whole
1837 # namespace and a push that started earlier may land after one that started
1838 # later. Eight parallel creates in one clone were enough: the pull reset the
1839 # counter from 7 to 4, the next two creates were handed 4 and 5 again, and
1840 # each overwrote the card already sitting on that ref (#172). The
1841 # compare-and-swap in allocate_next_id_ref cannot defend against this -- it is
1842 # the sole authority for handing out an id, but only while nothing else moves
1843 # the ref it counts on.
1844 #
1845 # The write is compare-and-swapped against the exact revision the comparison
1846 # was made on, so an allocation slipping in between makes the attempt lose and
1847 # read again instead of clobbering it. A local counter that is already ahead
1848 # is left alone and answered with KEPT_LOCAL -- applied, in that this is the
1849 # value both sides converge on and the next push publishes it, but not by
1850 # taking the remote's version, which is what keeps it out of the conflict
1851 # report.
1852 sub _adopt_next_id_ref {
1853 my ( $self, $oid ) = @_;
1854 my $repo = $self->_repo or return 0;
1855 my $remote_id = _parse_next_id( $self->_content_at_oid( $repo, $oid ) );
1856  
1857 my $why;
1858 my $ok = try {
1859 $self->_retry_untracked( sub {
1860 my ( $local_oid, $raw ) = $self->read_ref_with_oid(NEXT_ID_REF);
1861 return KEPT_LOCAL
1862 if defined $local_oid && _parse_next_id($raw) >= $remote_id;
1863 # 0 from the compare-and-swap is contention, not failure: read
1864 # again and decide again, never retry with the value that lost.
1865 return () unless $self->_cas_ref_oid( NEXT_ID_REF, $oid, $local_oid );
1866 return 1;
1867 } );
1868 } catch {
1869 # Same contract as _write_ref_untracked: a refusal is the caller's to
1870 # interpret, so it comes back as a false answer with the reason parked
1871 # in last_error, not as an exception out of the middle of a pull.
1872 $why = "$_";
1873 0;
1874 };
1875 $self->{_last_error} = $why if !$ok && defined $why;
1876 return $ok;
1877 }
1878  
1879 sub _same_oid {
1880 my ( $left, $right ) = @_;
1881 return 1 if !defined $left && !defined $right;
1882 return 0 if !defined $left || !defined $right;
1883 return $left eq $right ? 1 : 0;
1884 }
1885  
1886 # Ref writes that are not board work: reconciling with the remote, and keeping
1887 # the mirror up to date. They deliberately bypass write_ref/delete_ref so that
1888 # $WRITES stays a count of real board edits -- SyncGuard reads it to decide
1889 # whether anything still needs pushing, and counting a pull's own bookkeeping
1890 # there would make read-only commands claim they had unpushed work (#34).
1891 #
1892 # Contention is retried on exactly the terms write_ref and delete_ref use, and
1893 # for the same reason: losing the race for refs/<name>.lock is not a failed
1894 # write, it is a write that has not been attempted yet (#46). Skipping that
1895 # here was half of #154 -- one ref the remote had moved on was not applied
1896 # because another karr held its lock for a few microseconds.
1897 #
1898 # What they do not do is die when the retries run out or the write is refused
1899 # outright. Every caller is bookkeeping that has to decide for itself what a
1900 # miss means: the reconciliation loop has to finish the rest of its plan and
1901 # put the mirror back before it reports, and the mirror rollback behind a
1902 # refusal runs with another exception already on its way out. So the answer is
1903 # a boolean -- and it has to be checked, which is the other half of #154.
1904 sub _retry_untracked {
1905 my ( $self, $attempt ) = @_;
1906 for my $try ( 1 .. CAS_ATTEMPTS ) {
1907 my @answer = $attempt->();
1908 return $answer[0] if @answer;
1909 _cas_backoff($try);
1910 }
1911 return 0;
1912 }
1913  
1914 sub _write_ref_untracked {
1915 my ( $self, $ref, $oid ) = @_;
1916 my $repo = $self->_repo or return 0;
1917  
1918 # Only the failing outcome reaches last_error: a collision that cleared on
1919 # the second attempt is not something the next command that reads it
1920 # should find lying around.
1921 my $why;
1922 my $ok = $self->_retry_untracked( sub {
1923 my $wrote = try {
1924 $repo->reference_create( $ref, $oid, force => 1 );
1925 1;
1926 } catch {
1927 $why = _ref_error( 'write', $ref, $_ );
1928 return _is_contended_ref_error( $_, 0 ) ? undef : 0;
1929 };
1930 return () unless defined $wrote; # contended: not attempted yet
1931 return $wrote;
1932 } );
1933 $self->{_last_error} = $why if !$ok && defined $why;
1934 return $ok;
1935 }
1936  
1937 # "Gone" is the goal state, so a ref that is not there is this call's success
1938 # and not a failure to report -- unlike delete_ref, whose 0 answers the
1939 # different question of whether this call was the one that removed it (#119).
1940 sub _delete_ref_untracked {
1941 my ( $self, $ref ) = @_;
1942 my $repo = $self->_repo or return 0;
1943  
1944 my $why;
1945 my $ok = $self->_retry_untracked( sub {
1946 return 1 unless $repo->reference_exists($ref);
1947 my $deleted = try {
1948 $repo->reference_delete($ref);
1949 1;
1950 } catch {
1951 $why = _ref_error( 'delete', $ref, $_ );
1952 # Someone else got there first, which is this call's goal state.
1953 return 1 if blessed($_) && $_->isa('Git::Native::Error')
1954 && $_->is_not_found;
1955 return _is_contended_ref_error( $_, 0 ) ? undef : 0;
1956 };
1957 return () unless defined $deleted;
1958 return $deleted;
1959 } );
1960 $self->{_last_error} = $why if !$ok && defined $why;
1961 return $ok;
1962 }
1963  
1964 # The losing side of a conflict, kept reachable. Without this the displaced
1965 # local commit is unreferenced the moment the ref moves and the next gc takes
1966 # it, so "your edit was overwritten" would be a report with nothing behind it.
1967 # One slot per ref: bounded by board size, and a second conflict on the same
1968 # ref has already been reported once.
1969 #
1970 # Returns the parked ref name, or nothing when the park did not land -- in
1971 # which case the caller must leave the local ref alone rather than replace it
1972 # with the remote's, or the warning would point at a ref that was never
1973 # written and the local version really would be gone (#154).
1974 sub _park_conflicting_local {
1975 my ( $self, $remote, $ref, $oid ) = @_;
1976 my $parked =
1977 CONFLICT_ROOT . "/$remote/" . substr( $ref, length BOARD_ROOT );
1978 return unless $self->_write_ref_untracked( $parked, $oid );
1979 return $parked;
1980 }
1981  
1982 sub _warn_conflicts {
1983 my ( $self, $remote, $refs ) = @_;
1984 my $names = join ', ', map { substr $_, length BOARD_ROOT } @$refs;
1985 warn "karr: this clone and the remote both changed $names since the last "
1986 . "sync.\n"
1987 . "The remote version is now in place. The local one is kept at "
1988 . CONFLICT_ROOT . "/$remote/<name> and is never pushed.\n";
1989 return;
1990 }
1991  
1992 # Make the mirror follow what a push just published: %$local, the snapshot of
1993 # the board refs the push was built from, and @$deleted, the refs it told the
1994 # remote to drop. Nothing else -- a mirror slot the push did not touch belongs
1995 # to a ref another clone published, and claiming it here is how a card the
1996 # remote still has gets read as one the remote deleted (#178).
1997 #
1998 # The one place in this class where a ref write that does not land is harmless,
1999 # so the answers are deliberately not checked. A mirror slot left behind here
2000 # lags the remote instead of running ahead of it, and the next pull converges
2001 # on it either way: the local ref and the remote's already agree (L == R, the
2002 # first case in _reconcile_with_mirror), so the stale T is never consulted.
2003 # The failure mode #154 is about is the opposite one -- a mirror claiming an
2004 # OID that is not in place locally.
2005 sub _mirror_local_state {
2006 my ( $self, $remote, $local, $deleted, $root, $mirror_root ) = @_;
2007 return unless $self->_repo;
2008  
2009 $root //= BOARD_ROOT;
2010 my $prefix = $self->_mirror_prefix( $remote, $mirror_root );
2011 my $mirror = $self->ref_oids($prefix) || {};
2012  
2013 for my $ref ( keys %{ $local || {} } ) {
2014 my $name = $prefix . substr( $ref, length $root );
2015 next if _same_oid( $mirror->{$name}, $local->{$ref} );
2016 $self->_write_ref_untracked( $name, $local->{$ref} );
2017 }
2018 for my $ref ( @{ $deleted || [] } ) {
2019 my $name = $prefix . substr( $ref, length $root );
2020 $self->_delete_ref_untracked($name) if exists $mirror->{$name};
2021 }
2022 return;
2023 }
2024  
2025 # The tombstone for a ref whose deletions are published: same path, under the
2026 # tombstone root of its namespace. Returns nothing for a ref in a namespace
2027 # that has none -- pick locks, the tombstones themselves, the mirrors.
2028 sub _tombstone_name {
2029 my ( $self, $ref ) = @_;
2030 for my $ns (@TOMBSTONED) {
2031 my ( $root, $tomb ) = @$ns;
2032 return $tomb . '/' . substr( $ref, length $root )
2033 if index( $ref, $root ) == 0;
2034 }
2035 return;
2036 }
2037  
2038 # Record that this clone deleted $ref, so the next push tells the remote.
2039 # $oid is the OID the ref points at; read here when the caller does not
2040 # already hold it.
2041 #
2042 # Only the published namespaces leave a tombstone: pick locks under
2043 # refs/karr-local/ are never on the remote to begin with. A tombstone that
2044 # cannot be written is not an error the delete has to fail on -- it degrades to
2045 # a deletion the remote is not told about, which is the same place a killed
2046 # process leaves it, and raising here would fail a delete whose ref is about to
2047 # go regardless.
2048 sub _note_pending_delete {
2049 my ( $self, $ref, $oid ) = @_;
2050 my $tombstone = $self->_tombstone_name($ref) or return;
2051 $oid = ( $self->read_ref_with_oid($ref) )[0] unless defined $oid;
2052 return unless defined $oid;
2053 $self->_write_ref_untracked( $tombstone, $oid );
2054 return;
2055 }
2056  
2057 # The refs of one namespace this clone has deleted and not yet published, as
2058 # { ref => tombstone ref }. $root defaults to the board's.
2059 sub _pending_deletes {
2060 my ( $self, $root ) = @_;
2061 $root //= BOARD_ROOT;
2062 my ($ns) = grep { $_->[0] eq $root } @TOMBSTONED;
2063 return {} unless $ns;
2064  
2065 my $prefix = $ns->[1] . '/';
2066 my %pending;
2067 for my $name ( $self->list_refs($prefix) ) {
2068 $pending{ $root . substr( $name, length $prefix ) } = $name;
2069 }
2070 return \%pending;
2071 }
2072  
2073 # Drop the tombstones a successful push has settled: the ones it published as
2074 # deletions, and the stale ones it skipped because the ref was back on the
2075 # board. Only the ones this push read -- a tombstone another process wrote in
2076 # between is that push's to publish, not this one's to discard.
2077 #
2078 # A skipped one is re-checked rather than dropped on the strength of the
2079 # snapshot: the tombstone goes down before the ref does, so a delete running
2080 # in another process is briefly a tombstone whose ref is still there, and
2081 # clearing that on sight would throw away a deletion the push that made it has
2082 # not published yet.
2083 sub _clear_pending_deletes {
2084 my ( $self, $tombstones, $published ) = @_;
2085 my %published = map { $_ => 1 } @{ $published || [] };
2086 for my $ref ( sort keys %{ $tombstones || {} } ) {
2087 next if !$published{$ref} && !$self->ref_exists($ref);
2088 $self->_delete_ref_untracked( $tombstones->{$ref} );
2089 }
2090 return;
2091 }
2092  
2093 # The tombstones of $root settled without a push, for the clone that has no
2094 # remote to publish them to: the ones whose ref is really gone are dropped --
2095 # nobody is owed the news -- and so are the stale ones whose ref is back on the
2096 # board, while a delete still in flight in another process is left for the push
2097 # that will make it. Exactly the rules _clear_pending_deletes applies after a
2098 # push, which is why the genuinely deleted ones are handed to it as "published".
2099 #
2100 # The tombstones are read first and the namespace only when there are any: this
2101 # runs on every write in a repository without a remote, and there is almost
2102 # never anything to settle, so the one cheap scan answers for the common case
2103 # and the full one stays off the hot path.
2104 sub _settle_local_deletes {
2105 my ( $self, $root ) = @_;
2106 my $tombstones = $self->_pending_deletes($root);
2107 return unless %$tombstones;
2108  
2109 my $local = $self->ref_oids($root) || {};
2110 my @gone = grep { !exists $local->{$_} } sort keys %$tombstones;
2111 $self->_clear_pending_deletes( $tombstones, \@gone );
2112 return;
2113 }
2114  
2115 sub has_pending_deletes {
2116 my ($self) = @_;
2117 my @tombstones = $self->list_refs( TOMBSTONE_ROOT . '/' );
2118 return @tombstones ? 1 : 0;
2119 }
2120  
2121  
2122 sub push_ref {
2123 my ( $self, $ref, $remote ) = @_;
2124 $remote //= 'origin';
2125 $ref = $self->validate_helper_ref($ref);
2126 my $repo = $self->_repo or return 0;
2127 return 1 unless $repo->has_remote($remote);
2128 return $self->_push_refspecs( $remote, ["+$ref:$ref"] );
2129 }
2130  
2131  
2132 sub pull_ref {
2133 my ( $self, $ref, $remote ) = @_;
2134 $remote //= 'origin';
2135 $ref = $self->validate_helper_ref($ref);
2136 my $repo = $self->_repo or return 0;
2137 return 1 unless $repo->has_remote($remote);
2138 # Forced for the same reason as the board refspec (#40): helper refs are
2139 # written by write_ref too, so a helper ref that changed on the remote is
2140 # never a fast-forward and a non-forced fetch would leave `karr get-refs`
2141 # quietly serving the stale local copy.
2142 return $self->_fetch_refspecs( $remote, ["+$ref:$ref"] );
2143 }
2144  
2145  
2146 # ----- The fleet-coordination namespace: refs/karr-foundation/* (#190) -----
2147  
2148 sub pull_foundation {
2149 my ( $self, $remote ) = @_;
2150 $remote //= 'origin';
2151 my $repo = $self->_repo or return 0;
2152 return 1 unless $repo->has_remote($remote);
2153  
2154 my $prefix = $self->_mirror_prefix( $remote, FOUNDATION_MIRROR_ROOT );
2155  
2156 # The mirror as it stands now is the remote state at the last sync; the
2157 # fetch is about to overwrite it with the current one. Both are needed to
2158 # tell the four cases apart, so snapshot it first -- exactly as L</pull>
2159 # does, and for exactly the same reason.
2160 my $tracked = $self->ref_oids($prefix) || {};
2161  
2162 my $refspec = '+' . FOUNDATION_ROOT . '*:' . $prefix . '*';
2163 return 0 unless $self->_fetch_refspecs( $remote, [$refspec], prune => 1 );
2164  
2165 $self->_reconcile_foundation( $remote, $prefix, $tracked );
2166 return 1;
2167 }
2168  
2169  
2170 sub push_foundation {
2171 my ( $self, $remote ) = @_;
2172 $remote //= 'origin';
2173 my $repo = $self->_repo or return 0;
2174  
2175 # Same as L</push>, one namespace over: with no remote the tombstones have
2176 # no reader, and retention deletes fleet refs routinely (#197).
2177 unless ( $repo->has_remote($remote) ) {
2178 $self->_settle_local_deletes(FOUNDATION_ROOT);
2179 return 1;
2180 }
2181  
2182 # Read before the push, never after -- see L</push>: a ref written in
2183 # between is published without being in the snapshot, which leaves the
2184 # mirror lagging the remote, the direction that converges harmlessly.
2185 my $local = $self->ref_oids(FOUNDATION_ROOT) || {};
2186 my $tombstones = $self->_pending_deletes(FOUNDATION_ROOT);
2187 # A tombstone whose ref is back in the namespace is stale, not a deletion.
2188 my @deletes = grep { !exists $local->{$_} } sort keys %$tombstones;
2189  
2190 # Nothing here and nothing deleted is nothing to say, and saying it would
2191 # be an error: a wildcard refspec matching no local ref, sent on its own,
2192 # makes git exit non-zero ("No refs in common and none specified"), so
2193 # every repository that is not the hub would end `karr sync` complaining
2194 # about a namespace it does not have. This is also what keeps the second
2195 # round trip off the boards that never carry fleet state.
2196 return 1 unless %$local || @deletes;
2197  
2198 my @refspecs = ( FOUNDATION_REFSPEC, map { ":$_" } @deletes );
2199 return 0 unless $self->_push_refspecs( $remote, \@refspecs );
2200  
2201 $self->_mirror_local_state( $remote, $local, \@deletes,
2202 FOUNDATION_ROOT, FOUNDATION_MIRROR_ROOT );
2203 $self->_clear_pending_deletes( $tombstones, \@deletes );
2204 return 1;
2205 }
2206  
2207  
2208 sub _reconcile_foundation {
2209 my ( $self, $remote, $prefix, $tracked ) = @_;
2210 return unless $self->_repo;
2211  
2212 my ($plan) = $self->_mirror_plan( FOUNDATION_ROOT, $prefix, $tracked );
2213  
2214 my ( @conflicts, @unapplied, @stale );
2215 for my $step (@$plan) {
2216 my ( $ref, $oid, undef, $conflict ) = @$step;
2217 my $applied = defined $oid
2218 ? $self->_write_ref_untracked( $ref, $oid )
2219 : $self->_delete_ref_untracked($ref);
2220 if ($applied) {
2221 CORE::push @conflicts, $ref if $conflict;
2222 next;
2223 }
2224 # Same rule as the board's: the mirror goes back to what this ref had
2225 # before the fetch, and the pull stops (#154).
2226 CORE::push @unapplied, $ref;
2227 CORE::push @stale, $self->_rollback_mirror_ref(
2228 $prefix, $tracked, $ref, FOUNDATION_ROOT );
2229 }
2230  
2231 $self->_warn_foundation_conflicts( $remote, \@conflicts ) if @conflicts;
2232 die $self->_unapplied_refs_error( $remote, \@unapplied, \@stale )
2233 if @unapplied;
2234 return;
2235 }
2236  
2237 # Said, but not parked. The board keeps the losing side under
2238 # refs/karr-conflict/ because a displaced card is something a person reads back
2239 # and re-applies; a displaced chain step is a plan, and the answer to a plan
2240 # that lost a race is another planning round, not an archaeology dig. What is
2241 # worth saying is that it happened at all: two planners writing one chain is
2242 # the condition, and the operator is the only one who can end it.
2243 sub _warn_foundation_conflicts {
2244 my ( $self, $remote, $refs ) = @_;
2245 my $names = join ', ', map { substr $_, length FOUNDATION_ROOT } @$refs;
2246 warn "karr: this clone and the remote '$remote' both changed $names "
2247 . "under " . FOUNDATION_ROOT . " since the last sync.\n"
2248 . "The remote version is now in place and the local one is not kept. "
2249 . "Re-plan rather than re-edit.\n";
2250 return;
2251 }
2252  
2253 # Fallback transport via the system `git` CLI so that ssh-config directives
2254 # libgit2 ignores (ProxyCommand, Host aliases, IdentityFile, insteadOf) are
2255 # honoured. Returns 1 on success, 0 on failure (setting _last_error to the real
2256 # git-CLI stderr). $verb is 'push' or 'fetch'. @$refspecs may be empty
2257 # (fetch => configured refspecs). %opt: prune => bool. Disabled by
2258 # KARR_NO_CLI_FALLBACK=1.
2259 #
2260 # `push` runs with --porcelain so the per-ref outcomes come back parseable.
2261 # The CLI already exits non-zero on a rejection, so the failure was never
2262 # invisible here the way it was natively (#84) -- but the error contract has
2263 # to be the same on both transports, or "which ref did the server refuse, and
2264 # why" would depend on which one happened to run.
2265 sub _cli_transport {
2266 my ( $self, $verb, $remote, $refspecs, %opt ) = @_;
2267 return 0 if $ENV{KARR_NO_CLI_FALLBACK};
2268  
2269 my @args = ($verb);
2270 CORE::push @args, '--porcelain' if $verb eq 'push';
2271 CORE::push @args, '--prune' if $opt{prune};
2272 CORE::push @args, $remote, @$refspecs;
2273  
2274 my $native = $self->{_last_error};
2275 my $run = $self->_run_git(@args);
2276  
2277 if ( $run->{failure} eq 'start' ) {
2278 $self->{_last_error} =
2279 "git CLI fallback unavailable: $run->{err}"
2280 . ( defined $native ? " (native: $native)" : '' );
2281 return 0;
2282 }
2283  
2284 my $detail = $run->{err};
2285 $detail =~ s/\s+\z//;
2286 my $suffix = length $detail ? ": $detail" : '';
2287  
2288 if ( $run->{failure} eq 'timeout' ) {
2289 $self->{_last_error} = "git $verb (CLI fallback) timed out after "
2290 . "$run->{timeout}s and was killed$suffix";
2291 return 0;
2292 }
2293  
2294 # `$? >> 8` is 0 both for "exited cleanly" and for "died from a signal",
2295 # so a git the OOM killer, a Ctrl-C on the process group or a SIGPIPE took
2296 # down used to be reported as a successful transport -- the task was
2297 # announced as created and the remote never saw it (#42). The signal bits
2298 # have to be read first.
2299 if ( my $sig = $run->{status} & 127 ) {
2300 $self->{_last_error} =
2301 "git $verb (CLI fallback) was killed by signal $sig$suffix";
2302 return 0;
2303 }
2304 return 1 unless $run->{status} >> 8;
2305  
2306 if ( $verb eq 'push' ) {
2307 my $rejected = _parse_push_porcelain( $run->{out} );
2308 if (@$rejected) {
2309 $self->{_push_rejections} = $rejected;
2310 $self->{_last_error} =
2311 _push_rejection_error( $remote, $rejected,
2312 _count_push_porcelain_accepted( $run->{out} ) );
2313 return 0;
2314 }
2315 }
2316  
2317 $self->{_last_error} = "git $verb (CLI fallback) failed: $detail";
2318 return 0;
2319 }
2320  
2321 # `git push --porcelain` writes one machine-readable line per ref to stdout:
2322 #
2323 # <flag>TAB<src>:<dst>TAB<summary>
2324 #
2325 # '!' is the flag for a ref the far side refused, and the summary carries the
2326 # reason in parentheses -- "[remote rejected] (pre-receive hook declined)".
2327 # That is the CLI's equivalent of the push_update_reference status libgit2
2328 # reports, so parsing it is what makes both transports name the same refs with
2329 # the same reasons (#84).
2330 sub _parse_push_porcelain {
2331 my ($out) = @_;
2332 my @rejected;
2333 for my $line ( split /\n/, $out // '' ) {
2334 next unless $line =~ /\A!\t([^\t]*)\t(.*)\z/;
2335 my ( $refspec, $summary ) = ( $1, $2 );
2336 # "<src>:<dst>", and <src> is empty for a delete. The board ref is the
2337 # destination either way.
2338 my $ref = $refspec =~ /:([^:]*)\z/ ? $1 : $refspec;
2339 my $reason = $summary =~ /\(([^)]*)\)\s*\z/ ? $1 : $summary;
2340 CORE::push @rejected, { ref => $ref, reason => $reason };
2341 }
2342 return \@rejected;
2343 }
2344  
2345 # Everything that is not a rejection line and not git's own "To <url>" /
2346 # "Done" framing was a ref the server took, which is what turns the message
2347 # into "rejected 2 of 5" instead of a bare list.
2348 sub _count_push_porcelain_accepted {
2349 my ($out) = @_;
2350 my $accepted = 0;
2351 for my $line ( split /\n/, $out // '' ) {
2352 next unless $line =~ /\A([ +\-*=!])\t[^\t]*\t/;
2353 $accepted++ unless $1 eq '!';
2354 }
2355 return $accepted;
2356 }
2357  
2358 # Wall-clock budget for one `git` CLI run, in seconds. 0 (or a non-numeric
2359 # value) disables it. karr is driven by unattended agents, so the default is a
2360 # ceiling rather than a guess at how slow a legitimate transfer may be.
2361 use constant DEFAULT_TRANSPORT_TIMEOUT => 120;
2362  
2363 # Cap on how much of each stream is kept. Draining continues past it -- the
2364 # point is only to stop a runaway git from being buffered into memory whole.
2365 use constant CLI_OUTPUT_LIMIT => 65_536;
2366  
2367 sub _transport_timeout {
2368 my $raw = $ENV{KARR_TRANSPORT_TIMEOUT};
2369 return DEFAULT_TRANSPORT_TIMEOUT
2370 unless defined $raw && $raw =~ /\A\d+(?:\.\d+)?\z/;
2371 return $raw + 0;
2372 }
2373  
2374 # The budget for remote_has_board, which is not the transport budget: that one
2375 # is a ceiling for a transfer somebody asked for, this one bounds a round trip
2376 # nobody asked for, taken in front of a read command. A ref advertisement from
2377 # a reachable remote arrives in milliseconds over either transport, so ten
2378 # seconds is already an unreasonable remote rather than a slow one -- and it is
2379 # the budget for the whole probe, both of its attempts together.
2380 use constant BOARD_PROBE_TIMEOUT => 10;
2381  
2382 # KARR_TRANSPORT_TIMEOUT lowers it and never raises it, 0 ("no limit")
2383 # included: an unasked probe that can hang forever is the thing #173's guard
2384 # clause exists to avoid, and the answer it produces is only ever the
2385 # difference between fetching now and printing "run karr sync".
2386 sub _probe_timeout {
2387 my $configured = _transport_timeout();
2388 return BOARD_PROBE_TIMEOUT
2389 if !$configured || $configured > BOARD_PROBE_TIMEOUT;
2390 return $configured;
2391 }
2392  
2393 # Run `git -C <work tree root> @args` and return
2394 # { ok => 0|1, failure => ''|'start'|'timeout', status => $?, out, err,
2395 # timeout => $seconds }
2396 #
2397 # The root, not ->dir. Everything this class hands git as a path comes out of
2398 # _relative_to_root and is therefore measured from the work tree root, while a
2399 # git pathspec is resolved against the process cwd -- so running from ->dir
2400 # asked about `subdir/tasks` whenever ->dir was not the root, and `git ls-files`
2401 # answers that with exit 0 and no output, i.e. "not tracked" (#113). Pinning
2402 # the cwd here puts both routes on one origin instead of correcting the
2403 # pathspec at each call site. It costs the transport verbs nothing: git
2404 # discovers the same repository from either directory. Only a repository
2405 # libgit2 cannot open has no root to run from, and there ->dir is all that is
2406 # left -- the same degradation every other native operation makes.
2407 #
2408 # Both pipes are drained through one IO::Select loop. Reading stdout to EOF
2409 # first, as this used to, deadlocks the moment the child fills the 64 KiB
2410 # stderr pipe buffer: the child blocks on write and so never exits or closes
2411 # stdout, while the parent is still blocked reading stdout. A diverged board
2412 # reaches that at roughly 700 rejected refs, and it could strike inside
2413 # bin/karr's END flush, i.e. after the command had already printed its result
2414 # (#43). The loop is also bounded by a deadline, so a transport that stalls
2415 # (an ssh ProxyCommand hanging on a jump host, a grandchild holding the pipes
2416 # open past the child's exit) fails instead of hanging an unattended agent.
2417 #
2418 # `status` is the raw waitpid status, not `$? >> 8`, so callers can tell a
2419 # clean exit from a death by signal (#42).
2420 sub _run_git {
2421 my ( $self, @args ) = @_;
2422 # An optional leading hashref carries per-call options -- currently only
2423 # `timeout`, for the one caller whose budget is not the transport's
2424 # (remote_has_board, which runs unasked in front of a read command).
2425 # Every other caller passes git's argv and nothing else.
2426 my $opt = ref $args[0] eq 'HASH' ? shift @args : {};
2427  
2428 my $cwd = $self->repo_root // $self->dir;
2429 my @cmd = ( 'git', '-C', $cwd->stringify, @args );
2430 my $timeout = defined $opt->{timeout} ? $opt->{timeout} : _transport_timeout();
2431 my %result = (
2432 ok => 0, failure => 'start', status => 0,
2433 out => '', err => '', timeout => $timeout,
2434 );
2435  
2436 my ( $pid, $timed_out );
2437 my $started = try {
2438 local $ENV{GIT_TERMINAL_PROMPT} = 0; # never hang on an interactive prompt
2439 my $err_fh = gensym;
2440 $pid = open3( my $in, my $out_fh, $err_fh, @cmd );
2441 close $in;
2442  
2443 my %sink = (
2444 fileno($out_fh) => \$result{out},
2445 fileno($err_fh) => \$result{err},
2446 );
2447 my $select = IO::Select->new( $out_fh, $err_fh );
2448 my $deadline = $timeout ? Time::HiRes::time() + $timeout : undef;
2449  
2450 while ( $select->count ) {
2451 my $left = defined $deadline
2452 ? $deadline - Time::HiRes::time() : undef;
2453 if ( defined $left && $left <= 0 ) { $timed_out = 1; last }
2454 # Poll in slices so the deadline is still honoured while git is
2455 # quiet on both streams.
2456 my $slice = !defined $left || $left > 1 ? 1 : $left;
2457 for my $fh ( $select->can_read($slice) ) {
2458 my $read = sysread $fh, my $chunk, 65_536;
2459 if ( !defined $read ) {
2460 next if $! == EINTR;
2461 $select->remove($fh);
2462 next;
2463 }
2464 if ( !$read ) { $select->remove($fh); next }
2465 my $buffer = $sink{ fileno($fh) };
2466 $$buffer .= $chunk if length($$buffer) < CLI_OUTPUT_LIMIT;
2467 }
2468 }
2469 1;
2470 } catch {
2471 $result{err} = "$_";
2472 0;
2473 };
2474 return \%result unless $started;
2475  
2476 if ($timed_out) {
2477 $self->_reap_killed($pid);
2478 $result{failure} = 'timeout';
2479 return \%result;
2480 }
2481  
2482 waitpid $pid, 0;
2483 @result{qw( ok failure status )} = ( 1, '', $? );
2484 # The buffers hold raw bytes from the child git process, exactly like the
2485 # bytes config_string hands back: the :encoding(UTF-8) layer on the
2486 # binmode'd handle that reads them would encode them a second time on
2487 # their way out as a karr error message (#157). Decode here so callers
2488 # below this line see character strings, the same as the rest of the
2489 # class.
2490 $result{out} = from_octets( $result{out} );
2491 $result{err} = from_octets( $result{err} );
2492 return \%result;
2493 }
2494  
2495 # Take down a child that blew the transport timeout: TERM first, KILL if it is
2496 # still around, and reap it either way so it cannot linger as a zombie in a
2497 # long-running embedder.
2498 sub _reap_killed {
2499 my ( $self, $pid ) = @_;
2500 return unless $pid;
2501 kill 'TERM', $pid;
2502 for ( 1 .. 20 ) { # up to ~2s for a clean exit
2503 return if waitpid( $pid, WNOHANG ) > 0;
2504 Time::HiRes::sleep(0.1);
2505 }
2506 kill 'KILL', $pid;
2507 waitpid $pid, 0;
2508 return;
2509 }
2510  
2511 # ----- Board encoding contract (ticket #53) -----
2512  
2513 # karr up to 0.402 handed YAML::XS::Dump output (octets) around as if it were
2514 # characters, so every board written before this ref existed carries UTF-8
2515 # encoded twice in its task frontmatter, its config, and its activity log. The
2516 # ref is the discriminator: absent means "legacy, repair on read", 2 means
2517 # "written under the current contract, hands off". Boards are stamped by
2518 # `karr repair --yes`, and by `karr init` / `karr import --yes` when they
2519 # create the board rather than write into one that was already there -- see
2520 # App::karr::BoardStore/stamp_encoding_version for why that distinction is the
2521 # whole point (#132).
2522 #
2523 # Cached per object: it is consulted once per task load, and a board does not
2524 # change contract version mid-command.
2525 sub board_encoding_version {
2526 my ($self) = @_;
2527 return $self->{_encoding_version} //= do {
2528 my $raw = $self->read_ref('refs/karr/meta/encoding') // '';
2529 $raw =~ s/\s+//g;
2530 $raw =~ /\A(\d+)\z/ ? int($1) : 1;
2531 };
2532 }
2533  
2534  
2535 sub write_encoding_version {
2536 my ( $self, $version ) = @_;
2537 $version //= BOARD_ENCODING_VERSION;
2538 delete $self->{_encoding_version};
2539 return $self->write_ref( 'refs/karr/meta/encoding', "$version\n" );
2540 }
2541  
2542  
2543 sub board_is_legacy_encoded {
2544 my ($self) = @_;
2545 return $self->board_encoding_version < BOARD_ENCODING_VERSION ? 1 : 0;
2546 }
2547  
2548  
2549 # Repair board payloads read off a pre-contract board, and only those.
2550 sub maybe_repair_legacy {
2551 my ( $self, $data ) = @_;
2552 return $data unless $self->board_is_legacy_encoded;
2553 return repair_mojibake($data);
2554 }
2555  
2556  
2557 # ----- Board identity (ticket #95) -----
2558  
2559 # The wipe guard can only see ref counts, so a remote swapped for a different
2560 # non-empty board sailed straight through it. The board-id ref is the
2561 # discriminator the refs otherwise lacked: stamped once at board birth,
2562 # compared on every pull (see _check_board_identity).
2563  
2564 # Meta refs are plain text with a trailing newline; both sides of the
2565 # comparison go through this one normalization, or a formatting difference
2566 # would read as a foreign board.
2567 sub _read_id_ref {
2568 my ( $self, $ref ) = @_;
2569 my $raw = $self->read_ref($ref) // '';
2570 $raw =~ s/\s+//g;
2571 return length $raw ? $raw : undef;
2572 }
2573  
2574 sub read_board_id_ref {
2575 my ($self) = @_;
2576 return $self->_read_id_ref(BOARD_ID_REF);
2577 }
2578  
2579  
2580 sub write_board_id_ref {
2581 my ( $self, $id ) = @_;
2582 return $self->write_ref( BOARD_ID_REF, "$id\n" );
2583 }
2584  
2585  
2586 # 128 bits of hex. This is an accident guard, not a secret, and rand is the
2587 # same source App::karr::Cmd::AgentName uses; modern perls seed it from OS
2588 # entropy.
2589 sub new_board_id {
2590 my ($self) = @_;
2591 return join '', map { sprintf '%02x', int rand 256 } 1 .. 16;
2592 }
2593  
2594  
2595 # Read-before-write on purpose: an existing id is never re-keyed. That is
2596 # what makes re-init of a half-board safe -- re-keying would make every other
2597 # clone read this board as a foreign one.
2598 sub ensure_board_id_ref {
2599 my ($self) = @_;
2600 my $id = $self->read_board_id_ref;
2601 return $id if defined $id;
2602 $id = $self->new_board_id;
2603 $self->write_board_id_ref($id);
2604 return $id;
2605 }
2606  
2607  
2608 # ----- Task / config refs (sit on top of write_ref/read_ref) -----
2609  
2610 sub save_task_ref {
2611 my ($self, $task) = @_;
2612 my $ref = "refs/karr/tasks/" . $task->id . "/data";
2613 $self->write_ref($ref, $task->to_markdown);
2614 }
2615  
2616  
2617 sub load_task_ref {
2618 my ($self, $id) = @_;
2619 return ( $self->load_task_ref_with_oid($id) )[1];
2620 }
2621  
2622  
2623 # The task plus the OID of the commit it was read from, for callers that then
2624 # write it back under compare-and-swap (App::karr::Cmd::Pick). Same pairing
2625 # rule as read_ref_with_oid: guarding a write against an OID fetched
2626 # independently of the content would guard the wrong revision.
2627 sub load_task_ref_with_oid {
2628 my ($self, $id) = @_;
2629 my ($oid, $content) = $self->read_ref_with_oid("refs/karr/tasks/$id/data");
2630 return (undef, undef) unless defined $oid && length $content;
2631 return ($oid, App::karr::Task->from_string(
2632 $content,
2633 repair_frontmatter => $self->board_is_legacy_encoded,
2634 ));
2635 }
2636  
2637  
2638 sub save_task_ref_cas {
2639 my ($self, $task, $expected_old) = @_;
2640 my $ref = "refs/karr/tasks/" . $task->id . "/data";
2641 return $self->write_ref_cas($ref, $task->to_markdown, $expected_old);
2642 }
2643  
2644  
2645 # Only the data ref makes a task exist. The pattern used to be
2646 # m{refs/karr/tasks/(\d+)/}, which also matched .../N/lock -- so a lock left
2647 # behind by an agent that died mid-pick put its task id into this list even
2648 # after the card itself was deleted, load_tasks mapped that id to undef, and
2649 # every command that walks the board died on the undef. One orphaned lock ref
2650 # bricked the whole board with no way out from inside karr (#45).
2651 sub list_task_refs {
2652 my ($self) = @_;
2653 my %ids;
2654 for my $ref ( $self->list_refs('refs/karr/tasks/') ) {
2655 $ids{$1} = 1 if $ref =~ m{\Arefs/karr/tasks/(\d+)/data\z};
2656 }
2657 return sort { $a <=> $b } keys %ids;
2658 }
2659  
2660  
2661 sub list_refs {
2662 my ( $self, $prefix ) = @_;
2663 $prefix //= 'refs/karr/';
2664 my $repo = $self->_repo or return ();
2665 # Glob to scope the iterator server-side.
2666 my $names = $repo->reference_names( glob => "$prefix*" );
2667 return @$names;
2668 }
2669  
2670  
2671 sub ref_oids {
2672 my ( $self, $prefix ) = @_;
2673 $prefix //= 'refs/karr/';
2674 my $repo = $self->_repo or return undef;
2675 my %oids;
2676 for my $ref ( $self->list_refs($prefix) ) {
2677 my $oid = try {
2678 my $t = $repo->reference($ref)->target;
2679 $t ? $t->hex : undef;
2680 } catch { undef };
2681 $oids{$ref} = $oid if defined $oid;
2682 }
2683 return \%oids;
2684 }
2685  
2686  
2687 sub read_config_ref {
2688 my ($self) = @_;
2689 my $content = $self->read_ref('refs/karr/config');
2690 return {} unless $content;
2691 return $self->maybe_repair_legacy( yaml_load($content) );
2692 }
2693  
2694  
2695 sub write_config_ref {
2696 my ( $self, $data ) = @_;
2697 return $self->write_ref( 'refs/karr/config', yaml_dump($data) );
2698 }
2699  
2700  
2701 sub _parse_next_id {
2702 my ($raw) = @_;
2703 $raw = '' unless defined $raw;
2704 $raw =~ s/\s+\z//;
2705 return $raw =~ /^\d+$/ ? int($raw) : 1;
2706 }
2707  
2708 sub read_next_id_ref {
2709 my ($self) = @_;
2710 return _parse_next_id( $self->read_ref(NEXT_ID_REF) );
2711 }
2712  
2713  
2714 sub write_next_id_ref {
2715 my ( $self, $next_id ) = @_;
2716 return $self->write_ref( NEXT_ID_REF, "$next_id\n" );
2717 }
2718  
2719  
2720 # Hand out one id and move the counter past it in a single guarded step.
2721 #
2722 # The old read-then-write lost tasks outright: two agents that read the same
2723 # counter both got that id, wrote the same refs/karr/tasks/N/data, and the
2724 # loser's task was destroyed with both processes reporting success -- 40
2725 # parallel creates produced 32 tasks (#44). The counter has to be re-read
2726 # inside the loop, not once outside it: retrying with the value that already
2727 # lost would just lose again.
2728 sub allocate_next_id_ref {
2729 my ($self) = @_;
2730 return $self->retry_contended( 'the next-id counter', sub {
2731 my ( $oid, $raw ) = $self->read_ref_with_oid(NEXT_ID_REF);
2732 my $id = _parse_next_id($raw);
2733 return () unless $self->write_ref_cas( NEXT_ID_REF, ($id + 1) . "\n", $oid );
2734 return $id;
2735 } );
2736 }
2737  
2738  
2739 # ----- Whole-board replacement (restore) -----
2740  
2741 # The mirror image of validate_helper_ref, which keeps helper refs out of the
2742 # board namespace: a snapshot may only address refs inside it. Without this a
2743 # hand-edited backup could point refs/heads/main at a parentless karr commit,
2744 # because restore fed whatever keys the YAML carried straight to
2745 # reference_create.
2746 sub validate_board_ref {
2747 my ( $self, $ref ) = @_;
2748 defined $ref && length $ref
2749 or die "karr: snapshot contains a ref with no name\n";
2750 die "karr: '$ref' is outside the board namespace " . BOARD_ROOT . "\n"
2751 unless index( $ref, BOARD_ROOT ) == 0;
2752 die "karr: '$ref' is not a valid git ref name\n"
2753 unless Git::Native->reference_name_is_valid($ref);
2754 return $ref;
2755 }
2756  
2757  
2758 # Make the board consist of exactly the refs in %$refs (name => content).
2759 #
2760 # `karr restore` used to delete refs/karr/* first and write the snapshot back
2761 # one ref at a time, so anything that failed on the way took the board with it.
2762 # A single unusable ref name in the snapshot -- one that sorts before
2763 # refs/karr/config is enough -- left the board empty locally and on the remote,
2764 # because the END-block push insurance faithfully mirrored the half-executed
2765 # destruction, prune and all (#47). The tool people reach for when they are
2766 # already in trouble is the one that must not be able to make it worse.
2767 #
2768 # Nothing destructive happens here until the whole restore is known to be
2769 # writable. Phase one validates every name and builds every commit object;
2770 # neither touches a ref, so a failure leaves the board exactly as it was.
2771 # Phase two then overwrites in place instead of starting from an empty
2772 # namespace, so the board is never empty in between.
2773 #
2774 # Phase two is also atomic across its own writes: every ref's pre-restore
2775 # content is snapshotted before the first write, and any die out of
2776 # _write_ref_oid unwinds the writes that already landed before raising --
2777 # otherwise a write failure on the second of eight refs would leave a
2778 # board with the snapshot's config and the live board's tasks, which is
2779 # the half-apply disaster recovery is supposed to prevent (#155).
2780 sub replace_board_refs {
2781 my ( $self, $refs ) = @_;
2782 my $repo = $self->_repo
2783 or die "karr: no usable git repository: "
2784 . ( $self->last_error // 'unknown error' ) . "\n";
2785  
2786 my @wanted = sort keys %$refs;
2787 for my $ref (@wanted) {
2788 $self->validate_board_ref($ref);
2789 die "karr: snapshot value for '$ref' is not text\n" if ref $refs->{$ref};
2790 }
2791  
2792 my %commit;
2793 for my $ref (@wanted) {
2794 $commit{$ref} =
2795 $self->_commit_for_content( $repo, $refs->{$ref} // '' );
2796 }
2797  
2798 # Snapshot the current OID+content of every ref the restore is about to
2799 # touch, so a phase-two failure can put each one back where it was.
2800 # Anything that existed before the restore but is not in @wanted is also
2801 # captured, because the cleanup loop below would have deleted it on
2802 # success and the unwind has to undo that too.
2803 my %pre_exist = map { $_ => 1 } $self->list_refs(BOARD_ROOT);
2804 my %pre_oid;
2805 for my $ref ( sort keys %pre_exist, @wanted ) {
2806 my ($oid) = $self->read_ref_with_oid($ref);
2807 $pre_oid{$ref} = $oid;
2808 }
2809  
2810 my $undo = sub {
2811 # Restore every ref that was here before the restore, including the
2812 # ones the cleanup loop would have removed, and delete anything the
2813 # snapshot managed to land before the failure. The goal is "the board
2814 # reads back exactly as it did before this call entered", not a
2815 # best-effort cleanup, so the failures themselves are warned but not
2816 # raised -- the original exception is the one the caller wants to see.
2817 for my $ref ( sort keys %pre_oid ) {
2818 my $pre_oid = $pre_oid{$ref};
2819 my $now_oid = ( $self->read_ref_with_oid($ref) )[0];
2820 next if defined $pre_oid && defined $now_oid && $pre_oid eq $now_oid;
2821 try {
2822 if ( defined $pre_oid ) {
2823 $repo->reference_create( $ref, $pre_oid, force => 1 );
2824 } else {
2825 $repo->reference_delete($ref);
2826 }
2827 } catch {
2828 warn "karr: failed to roll $ref back after restore error: $_\n";
2829 };
2830 }
2831 };
2832  
2833 try {
2834 $self->_write_ref_oid( $_, $commit{$_} ) for @wanted;
2835 } catch {
2836 $undo->();
2837 die $_;
2838 };
2839  
2840 # Only now the refs the snapshot does not carry. One left behind means the
2841 # board holds more than the snapshot did -- worth saying out loud, but not
2842 # worth failing a restore whose data is already in place.
2843 #
2844 # This is the one caller that wants a refused delete to be survivable, so
2845 # it is the one that catches it (#119). A 0 is not a refusal and not stuck:
2846 # it means the ref went between the listing and the delete.
2847 my @stuck;
2848 for my $ref ( $self->list_refs(BOARD_ROOT) ) {
2849 next if exists $commit{$ref};
2850 my $gone = try { $self->delete_ref($ref); 1 } catch { 0 };
2851 CORE::push @stuck, $ref unless $gone;
2852 }
2853 warn "karr: restored the snapshot, but could not remove "
2854 . join( ', ', @stuck ) . "\n" if @stuck;
2855  
2856 # The snapshot may carry a different meta/encoding than the board had.
2857 delete $self->{_encoding_version};
2858 return 1;
2859 }
2860  
2861  
2862 sub delete_refs {
2863 my ( $self, $prefix ) = @_;
2864  
2865 # One ref refusing to go must not stop the others, or the report below
2866 # would name whichever failed first instead of everything still standing.
2867 # delete_ref dies on a refusal now (#119), and that exception is the only
2868 # thing that says *why* a `karr destroy` is stuck -- so it is kept, not
2869 # swallowed, and raised after every ref has had its turn.
2870 my @why;
2871 for my $ref ( $self->list_refs($prefix) ) {
2872 try { $self->delete_ref($ref) } catch { CORE::push @why, $_ };
2873 }
2874  
2875 # Re-read rather than trust the loop. Now that delete_ref can say no
2876 # (#51), swallowing that here would just move the old lie one level up and
2877 # let `karr destroy` report success over refs that are still on disk. It is
2878 # also the only answer that stays right when a ref vanished underneath us:
2879 # gone is gone, whoever removed it.
2880 my @left = $self->list_refs($prefix);
2881 return 1 unless @left;
2882 die join( '', @why ) if @why;
2883 die "karr: could not delete " . join( ', ', @left ) . "\n";
2884 }
2885  
2886  
2887 1;
2888  
2889 __END__
« blib/lib/App/karr/Cmd/Context.pm ↑ Summary blib/lib/App/karr/Foundation.pm »