Skip to content

Git designed for AI agents.

graft: the lane resolves the rules, as v0.2.0 did, and a land enters the lane first

Federico Elia2674a4c57e95
diff --git a/internal/gitaly/config/config_graft.go b/internal/gitaly/config/config_graft.go
index 3804297..327cfd3 100644
--- a/internal/gitaly/config/config_graft.go
+++ b/internal/gitaly/config/config_graft.go
@@ -311,6 +311,12 @@ type GraftResolver struct {
// Timeout bounds one resolver call, as a Go duration ("120s"). Empty means
// DefaultGraftResolverTimeout.
Timeout string `json:"timeout" toml:"timeout,omitempty"`
+ // InlineTimeout bounds the call that the lane makes to resolve a member's conflicting files inline
+ // (PLAN10 15.8), as a Go duration ("1s"). Empty means DefaultGraftResolverInlineTimeout; "0s"
+ // turns the inline resolution off. The lane asks the resolver for its rules only; if the call does
+ // not end in time, the member goes back out of the lane, to be resolved there. Without
+ // verify.enabled only: with a verification every tree is verified out of the lane.
+ InlineTimeout string `json:"inline_timeout" toml:"inline_timeout,omitempty"`
// MaxFiles bounds the number of conflicting files sent in one request; a
// conflict touching more files is not sent. Zero means
// DefaultGraftResolverMaxFiles.
@@ -604,6 +610,9 @@ func (r GraftResolver) validate() error {
if _, err := r.TimeoutOrDefault(); err != nil {
return err
}
+ if _, err := r.InlineTimeoutOrDefault(); err != nil {
+ return err
+ }
if _, err := r.ProposalTTLOrDefault(); err != nil {
return err
}
@@ -665,6 +674,22 @@ func (r GraftResolver) TimeoutOrDefault() (time.Duration, error) {
return d, nil
}
+// DefaultGraftResolverInlineTimeout is the default of GraftResolver.InlineTimeout.
+const DefaultGraftResolverInlineTimeout = "1s"
+
+// InlineTimeoutOrDefault parses InlineTimeout, applying the default. Zero turns the inline resolution off.
+func (r GraftResolver) InlineTimeoutOrDefault() (time.Duration, error) {
+ s := r.InlineTimeout
+ if s == "" {
+ s = DefaultGraftResolverInlineTimeout
+ }
+ d, err := time.ParseDuration(s)
+ if err != nil || d < 0 {
+ return 0, fmt.Errorf("graft land resolver: invalid inline_timeout %q", r.InlineTimeout)
+ }
+ return d, nil
+}
+
// DefaultGraftResolverCheckConcurrency is the default of GraftResolver.CheckConcurrency.
const DefaultGraftResolverCheckConcurrency = 2
diff --git a/internal/gitaly/service/operations/land_inline.go b/internal/gitaly/service/operations/land_inline.go
new file mode 100644
index 0000000..7c2e0fe
--- /dev/null
+++ b/internal/gitaly/service/operations/land_inline.go
@@ -0,0 +1,126 @@
+package operations
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/feder-cr/git-ai/internal/git"
+ "github.com/feder-cr/git-ai/internal/gitaly/hook"
+ "github.com/feder-cr/git-ai/internal/graft/identity"
+ "github.com/feder-cr/git-ai/internal/graft/resolver"
+ "github.com/feder-cr/git-ai/proto/go/gitalypb"
+)
+
+// Inline resolution of the rules in the lane (PLAN10 15.8).
+//
+// A land with conflicts is resolved out of the lane, because a model takes minutes and the lane is the
+// branch's. But a rule (trivial, union, rerere, a command that is a rule) takes milliseconds, and for the
+// lands on a hot file the out-of-lane resolution costs a round trip through the lane for every landing:
+// the member that lands alone in a batch of its own pays the batch's fixed cost (the pack, the reference
+// update, the replay) once more. As in v0.2.0, the lane therefore resolves a member's missing files
+// itself, so that the members ride the same batches, but only what a rule can do and only within a
+// bound of time:
+//
+// - the request asks for the rules only (Request.RulesOnly): graft-resolve never calls a model for it,
+// and says so in its answer (Response.RulesOnly). The split follows what the resolution is, not how
+// long the last one took;
+// - the call is bounded by inline_timeout (default 1s); if it does not end in time, or does not resolve
+// every missing file as a rule, the member goes back out of the lane, as it did before, to be resolved
+// there, with the queue of land_tickets.go;
+// - a resolver that does not echo RulesOnly is an older graft-resolve, which may have called a model: the
+// answer is dropped, and the lane never resolves inline again for the life of the process;
+// - with a verification (verify.enabled) the lane never resolves: every tree is verified out of the lane;
+// - the answer is validated like any other (the client's acceptance rules, the modes, the origin), and
+// decideLand is the same: an answer that is not a rule's is never taken here.
+
+// landInlineEnabled reports whether the lane resolves the rules inline: it is configured (inline_timeout is
+// not zero), there is no verification, and the resolver has not shown itself to be an older one.
+func (s *Server) landInlineEnabled() bool {
+ timeout, err := s.resolveCfg.InlineTimeoutOrDefault()
+ return err == nil && timeout > 0 && !s.resolveCfg.Verify.Enabled && !s.landInlineOff.Load() && s.conflictResolver != nil
+}
+
+// landResolveInline resolves, in the lane, the conflicting files of the member that have no verdict, as
+// the rules would, and keeps the verdicts. It reports whether every one of them has a verdict now; it
+// changes nothing when it reports false.
+func (s *Server) landResolveInline(ctx context.Context, in *gitalypb.UserLandRequest, tip, commitID git.ObjectID, l landListing, pre *landPreResolution) bool {
+ if !s.landInlineEnabled() || pre.unverifiable != "" {
+ return false
+ }
+ timeout, _ := s.resolveCfg.InlineTimeoutOrDefault()
+ // An agent that may not update the branch gets nothing resolved, as out of the lane (the policy first):
+ // the land goes out of the lane, which refuses it with the policy's message.
+ reference := git.NewReferenceNameFromBranchName(string(in.GetBranch()))
+ if err := hook.CheckAgentPolicy(ctx, s.graft, fmt.Sprintf("%s %s %s\n", tip, commitID, reference)); err != nil {
+ return false
+ }
+
+ var pending []*landFileState
+ var sent []resolver.File
+ for _, f := range l.files {
+ if _, ok := pre.verdicts[landKeyOf(f.conflict)]; ok {
+ continue
+ }
+ if !f.sent() {
+ // A file that may not be sent to the resolver is not resolved: the land goes out of the lane
+ // and says why.
+ return false
+ }
+ pending = append(pending, f)
+ sent = append(sent, landRequestFile(f))
+ }
+ if len(pending) == 0 {
+ return false
+ }
+
+ req := resolver.Request{
+ Version: resolver.ProtocolVersion,
+ Repository: resolver.Repository{
+ Storage: in.GetRepository().GetStorageName(),
+ RelativePath: in.GetRepository().GetRelativePath(),
+ },
+ Branch: string(in.GetBranch()),
+ Commit: commitID.String(),
+ Messages: resolver.Messages{Commit: l.commitMessage},
+ Actor: identity.Actor(ctx, ""),
+ Files: sent,
+ Capabilities: resolver.ServerCapabilities(),
+ RulesOnly: true,
+ }
+ callCtx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ resp, err := s.landResolveSlotted(callCtx, req)
+ if err != nil {
+ // Out of time, or the rules cannot resolve a file: the member is resolved out of the lane.
+ s.logger.WithError(err).WithField("branch", string(in.GetBranch())).Debug("graft: inline resolution handed back")
+ return false
+ }
+ if !resp.RulesOnly {
+ if s.landInlineOff.CompareAndSwap(false, true) {
+ s.logger.WithField("resolver", resp.Resolver).Warn("graft: the resolver did not honour a request for its rules only (an older graft-resolve): the lane resolves out of the lane from now on")
+ }
+ return false
+ }
+ if !landResolverNameValid(resp.Resolver) {
+ return false
+ }
+ landNormalizeOrigins(resp)
+ byPath := make(map[string]resolver.ResponseFile, len(resp.Files))
+ for _, rf := range resp.Files {
+ if rf.FromModel() || rf.Hold != "" {
+ // Never a model's in the lane, whatever was asked.
+ return false
+ }
+ byPath[rf.Path] = rf
+ }
+ for _, f := range pending {
+ rf, ok := byPath[f.conflict.path]
+ if !ok || landModeOfSides(f.conflict, rf) != nil {
+ return false
+ }
+ }
+ for _, f := range pending {
+ pre.verdicts[landKeyOf(f.conflict)] = landVerdict{file: byPath[f.conflict.path], resolver: resp.Resolver}
+ }
+ return true
+}
diff --git a/internal/gitaly/service/operations/land_inline_test.go b/internal/gitaly/service/operations/land_inline_test.go
new file mode 100644
index 0000000..0fa457f
--- /dev/null
+++ b/internal/gitaly/service/operations/land_inline_test.go
@@ -0,0 +1,177 @@
+package operations
+
+import (
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+
+ "github.com/feder-cr/git-ai/internal/git"
+ "github.com/feder-cr/git-ai/internal/gitaly/config"
+ "github.com/feder-cr/git-ai/internal/graft/identity"
+)
+
+// The tests of the inline resolution of the rules in the lane (land_inline.go), with the resolver of
+// land_queue_test.go: a union of the sides, a rule.
+
+// landAll lands the commits at the same time and returns the error of each.
+func (q queueFixture) landAll(commits []git.ObjectID) []error {
+ var wg sync.WaitGroup
+ errs := make([]error, len(commits))
+ for i, c := range commits {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, errs[i] = q.land(c)
+ }()
+ }
+ wg.Wait()
+ return errs
+}
+
+func inlineOn(c *config.GraftResolver) { c.InlineTimeout = "" } // the default: on
+
+// TestUserLand_theRulesAreResolvedInTheLane: with resolve_rounds of 1, a land that loses its first round has
+// no second one, and still lands: the lane resolves it, as the rules do, within the batch. The control, with
+// the inline resolution off, does lose lands to the cap.
+func TestUserLand_theRulesAreResolvedInTheLane(t *testing.T) {
+ t.Parallel()
+
+ const lands = 8
+ tune := func(inline bool) func(*config.GraftResolver) {
+ return func(c *config.GraftResolver) {
+ c.ResolveRounds = 1
+ if inline {
+ inlineOn(c)
+ } else {
+ c.InlineTimeout = "0s"
+ }
+ }
+ }
+
+ on := newQueueFixture(t, lands, tune(true))
+ for i, err := range on.landAll(on.onA) {
+ require.NoError(t, err, "land %d of %d with resolve_rounds 1", i+1, lands)
+ }
+ require.Len(t, strings.Split(on.branchBlob(t, "a"), "\n"), lands+1, "every land is in the file")
+ require.Positive(t, inlineCalls(t, on.dir), "the lane asked for the rules only")
+
+ off := newQueueFixture(t, lands, tune(false))
+ failed := 0
+ for _, err := range off.landAll(off.onA) {
+ if err != nil {
+ failed++
+ }
+ }
+ require.Positive(t, failed, "the control: without the inline resolution the cap of 1 round ends lands")
+ require.Zero(t, inlineCalls(t, off.dir))
+}
+
+// TestUserLand_aRuleThatDoesNotEndInTimeIsHandedBack: the rule takes 3 s and the lane gives it 300 ms: the
+// member goes out of the lane, and is resolved there (the resolver answers the ordinary request at once).
+func TestUserLand_aRuleThatDoesNotEndInTimeIsHandedBack(t *testing.T) {
+ t.Parallel()
+
+ q := newQueueFixtureMode(t, 3, "slow", func(c *config.GraftResolver) { c.InlineTimeout = "300ms" })
+ start := time.Now()
+ for i, err := range q.landAll(q.onA) {
+ require.NoError(t, err, "land %d", i+1)
+ }
+ require.Less(t, time.Since(start), 60*time.Second)
+ require.Positive(t, inlineCalls(t, q.dir), "the lane tried")
+ require.Len(t, strings.Split(q.branchBlob(t, "a"), "\n"), 4)
+}
+
+// TestUserLand_anOlderResolverIsNeverAskedAgain: a resolver that does not say that it honoured the request
+// for the rules only may have called a model: its answer is not taken, the lane never asks again for the life
+// of the process (lands that were already in the lane when the first answer came may have asked too), and
+// the lands go on out of the lane.
+func TestUserLand_anOlderResolverIsNeverAskedAgain(t *testing.T) {
+ t.Parallel()
+
+ var s *Server
+ operationServerHooks.Store(t.Name(), func(served *Server) { s = served })
+ q := newQueueFixtureMode(t, 10, "noecho", func(c *config.GraftResolver) { c.InlineTimeout = "" })
+ require.NotNil(t, s, "the service's own Server")
+
+ for i, err := range q.landAll(q.onA[:5]) {
+ require.NoError(t, err, "land %d", i+1)
+ }
+ require.True(t, s.landInlineOff.Load(), "the lane stopped asking")
+ asked := inlineCalls(t, q.dir)
+ require.Positive(t, asked)
+
+ for i, err := range q.landAll(q.onA[5:]) {
+ require.NoError(t, err, "land %d of the second wave", i+1)
+ }
+ require.Equal(t, asked, inlineCalls(t, q.dir), "not asked again")
+ require.Len(t, strings.Split(q.branchBlob(t, "a"), "\n"), 11)
+}
+
+// TestUserLand_withAVerificationTheLaneNeverResolves: every tree is verified out of the lane, so the lane
+// is not asked for anything.
+func TestUserLand_withAVerificationTheLaneNeverResolves(t *testing.T) {
+ t.Parallel()
+
+ _, vargv := countingVerify(t, "exit 0")
+ q := newQueueFixture(t, 4, func(c *config.GraftResolver) {
+ c.InlineTimeout = ""
+ *c = withVerify(*c, vargv, "")
+ })
+ for i, err := range q.landAll(q.onA) {
+ require.NoError(t, err, "land %d", i+1)
+ }
+ require.Zero(t, inlineCalls(t, q.dir))
+}
+
+// TestUserLand_theLaneIsEnteredFirstWhenItResolvesTheRules: with the inline resolution on, a land enters the
+// lane at once: a land without conflicts is never pre-resolved (the resolver is not called), and one with
+// conflicts that a rule resolves is resolved in the lane by one request for the rules only, with none out
+// of the lane.
+func TestUserLand_theLaneIsEnteredFirstWhenItResolvesTheRules(t *testing.T) {
+ t.Parallel()
+
+ q := newQueueFixture(t, 1, func(c *config.GraftResolver) { c.InlineTimeout = "" })
+
+ // The land on b only has its conflicts resolved in the lane.
+ _, err := q.land(q.onlyB)
+ require.NoError(t, err)
+ require.Equal(t, 1, unionCalls(t, q.dir))
+ require.Equal(t, 1, inlineCalls(t, q.dir), "the one request was the lane's, for the rules only")
+
+ // And the other one too.
+ _, err = q.land(q.onA[0])
+ require.NoError(t, err)
+ require.Equal(t, 2, unionCalls(t, q.dir))
+ require.Equal(t, 2, inlineCalls(t, q.dir), "no request out of the lane")
+ require.Equal(t, []string{"ours", "theirs-0"}, strings.Split(q.branchBlob(t, "a"), "\n")[:2])
+}
+
+// TestLandResolveInline_neverForAnAgentThePolicyDenies: the policy comes first, as out of the lane: an agent
+// that may not update the branch gets nothing resolved in the lane either, and the land goes out of it, where
+// the policy refuses it.
+func TestLandResolveInline_neverForAnAgentThePolicyDenies(t *testing.T) {
+ t.Parallel()
+
+ dir, argv := unionResolverMode(t, "")
+ rcfg := enabledResolver(argv)
+ rcfg.InlineTimeout = ""
+ fx := newResolveFixture(t, rcfg)
+ s := fx.server(t, rcfg)
+ s.graft = config.Graft{Standalone: true, Policy: []config.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/other"}, Allow: true}}}
+ ctx := identity.NewContext(fx.ctx, identity.Identity{Name: "agent-7", Source: identity.SourceAgent})
+
+ l, err := landListConflicts(ctx, fx.repo, fx.tip, fx.commit, 1<<20)
+ require.NoError(t, err)
+ require.NoError(t, s.landClassify(ctx, fx.repo, l.files, l.base, fx.tip, fx.commit, newLandClassifyCache(l.files, fx.tip)))
+ pre := newLandPreResolution()
+ require.False(t, s.landResolveInline(ctx, fx.request("Land"), fx.tip, fx.commit, l, pre), "denied by the policy")
+ require.Zero(t, unionCalls(t, dir), "nothing was resolved")
+
+ // The same agent where the policy lets it update the branch.
+ s.graft.Policy = []config.GraftPolicyRule{{Actor: "agent-7", Refs: []string{"refs/heads/**"}, Allow: true}}
+ require.True(t, s.landResolveInline(ctx, fx.request("Land"), fx.tip, fx.commit, l, pre))
+ require.Equal(t, 1, unionCalls(t, dir))
+}
diff --git a/internal/gitaly/service/operations/land_preresolve.go b/internal/gitaly/service/operations/land_preresolve.go
index ce5ccfd..6e5417b 100644
--- a/internal/gitaly/service/operations/land_preresolve.go
+++ b/internal/gitaly/service/operations/land_preresolve.go
@@ -276,9 +276,18 @@ func (s *Server) landResolving(ctx context.Context, in *gitalypb.UserLandRequest
pre.ticket.release()
landResolutionRounds.Observe(float64(used))
}()
+ // When the lane resolves the rules itself (land_inline.go), the first round enters it at once: a land
+ // without conflicts needs no pre-resolution at all, and one with conflicts that a rule resolves is
+ // resolved there, in its batch. What the rules cannot resolve is handed back, and resolved out of the
+ // lane in the next round.
+ laneFirst := s.landInlineEnabled()
for round := 1; round <= rounds; round++ {
used = round
- if err := s.landPreResolve(resolveCtx, in, committer, pre); err != nil {
+ var preErr error
+ if !(round == 1 && laneFirst) {
+ preErr = s.landPreResolve(resolveCtx, in, committer, pre)
+ }
+ if err := preErr; err != nil {
// The deadline ended a step of the round: the listing, the tree, the resolution or the
// verification. A refusal of the policy is not a deadline.
if deadline() && status.Code(err) != codes.PermissionDenied {
diff --git a/internal/gitaly/service/operations/land_queue_test.go b/internal/gitaly/service/operations/land_queue_test.go
index 0415253..bddcb16 100644
--- a/internal/gitaly/service/operations/land_queue_test.go
+++ b/internal/gitaly/service/operations/land_queue_test.go
@@ -23,18 +23,32 @@ import (
// unionResolver writes a resolver command that resolves every file of the request with the union of the
// lines of the two sides, as a rule, and counts its runs in dir/calls.log. The runs are concurrent, so
-// each reads its own request file.
+// each reads its own request file. It honours a request for the rules only, and counts those requests
+// in dir/inline.log.
func unionResolver(t *testing.T) (string, []string) {
t.Helper()
+ return unionResolverMode(t, "")
+}
+
+// unionResolverMode is unionResolver with a mode: "slow" takes 3 s to answer a request for the rules only
+// (a rule that does not end in time), "noecho" does not say that it honoured the request (an older
+// graft-resolve).
+func unionResolverMode(t *testing.T, mode string) (string, []string) {
+ t.Helper()
dir := t.TempDir()
script := fmt.Sprintf(`#!/bin/sh
DIR='%s'
echo x >> "$DIR/calls.log"
cat > "$DIR/req-$$.json"
-python3 - "$DIR/req-$$.json" <<'PY'
-import base64, json, sys
+python3 - "$DIR/req-$$.json" "$DIR" '%s' <<'PY'
+import base64, json, sys, time
req = json.load(open(sys.argv[1]))
+rules = bool(req.get("rules_only"))
+if rules:
+ open(sys.argv[2] + "/inline.log", "a").write("x\n")
+ if sys.argv[3] == "slow":
+ time.sleep(3)
files = []
for f in req["files"]:
ours = base64.b64decode(f["ours"]["content"]).decode().splitlines()
@@ -42,14 +56,29 @@ for f in req["files"]:
merged = ours + [l for l in theirs if l not in ours]
files.append({"path": f["path"], "action": "write", "mode": "100644", "origin": "rule",
"content": base64.b64encode(("\n".join(merged) + "\n").encode()).decode()})
-json.dump({"version": 1, "resolver": "graft-resolve/union", "files": files}, sys.stdout)
+resp = {"version": 1, "resolver": "graft-resolve/union", "files": files}
+if sys.argv[3] != "noecho":
+ resp["rules_only"] = rules
+json.dump(resp, sys.stdout)
PY
-`, dir)
+`, dir, mode)
path := filepath.Join(dir, "resolver.sh")
require.NoError(t, os.WriteFile(path, []byte(script), 0o755))
return dir, []string{path}
}
+// inlineCalls is the number of requests for the rules only that the resolver of dir got.
+func inlineCalls(t *testing.T, dir string) int {
+ t.Helper()
+
+ raw, err := os.ReadFile(filepath.Join(dir, "inline.log"))
+ if os.IsNotExist(err) {
+ return 0
+ }
+ require.NoError(t, err)
+ return len(raw) / 2
+}
+
// unionCalls is the number of runs of the resolver of dir.
func unionCalls(t *testing.T, dir string) int {
t.Helper()
@@ -78,8 +107,13 @@ type queueFixture struct {
func newQueueFixture(t *testing.T, n int, tune func(*config.GraftResolver)) queueFixture {
t.Helper()
+ return newQueueFixtureMode(t, n, "", tune)
+}
+
+func newQueueFixtureMode(t *testing.T, n int, mode string, tune func(*config.GraftResolver)) queueFixture {
+ t.Helper()
- dir, argv := unionResolver(t)
+ dir, argv := unionResolverMode(t, mode)
rcfg := enabledResolver(argv)
if tune != nil {
tune(&rcfg)
diff --git a/internal/gitaly/service/operations/land_resolve.go b/internal/gitaly/service/operations/land_resolve.go
index fdded7a..ca9fe17 100644
--- a/internal/gitaly/service/operations/land_resolve.go
+++ b/internal/gitaly/service/operations/land_resolve.go
@@ -524,6 +524,16 @@ func (s *Server) landApplyVerdicts(
Warn("graft: the merge at the lane's tip has conflicts without a conflicting file")
return landResolution{}, l.notAttempted(landNoConflictingFiles, nil)
}
+ // The rules are resolved here, in the lane, within a bound of time (land_inline.go): the member rides
+ // the batch, as it did before the resolution left the lane. What a rule cannot resolve goes out.
+ if len(missing) > 0 && pre != nil && s.conflictResolver != nil && l.bases <= 1 && s.landResolveInline(ctx, in, tip, commitID, l, pre) {
+ missing = missing[:0]
+ for _, f := range l.files {
+ if _, ok := pre.verdicts[landKeyOf(f.conflict)]; !ok || !f.sent() {
+ missing = append(missing, f.conflict.path)
+ }
+ }
+ }
if len(missing) > 0 {
return landResolution{}, &landNeedsResolution{tip: tip, commit: commitID, paths: missing}
}
diff --git a/internal/gitaly/service/operations/land_resolve_test.go b/internal/gitaly/service/operations/land_resolve_test.go
index 6d2d007..6b61762 100644
--- a/internal/gitaly/service/operations/land_resolve_test.go
+++ b/internal/gitaly/service/operations/land_resolve_test.go
@@ -108,8 +108,11 @@ func validAnswer() resolver.Response {
// enabledResolver is a resolver configuration with resolution on, the given command and every
// default.
+//
+// The inline resolution of the rules in the lane (land_inline.go) is off here: most of these tests are about
+// what happens out of the lane, with rounds, and the tests of the inline resolution turn it on.
func enabledResolver(argv []string) config.GraftResolver {
- return config.GraftResolver{Enabled: true, Command: argv}
+ return config.GraftResolver{Enabled: true, Command: argv, InlineTimeout: "0s"}
}
// gitBinary returns the absolute path of the git executable Gitaly runs, for scripts that move
diff --git a/internal/gitaly/service/operations/server.go b/internal/gitaly/service/operations/server.go
index 2b8c4a5..244acbf 100644
--- a/internal/gitaly/service/operations/server.go
+++ b/internal/gitaly/service/operations/server.go
@@ -2,6 +2,7 @@ package operations
import (
"context"
+ "sync/atomic"
"github.com/feder-cr/git-ai/internal/git/catfile"
"github.com/feder-cr/git-ai/internal/git/localrepo"
@@ -53,6 +54,9 @@ type Server struct {
// landResolveHook, when set, runs in every resolver call while it holds its resolve slot; only
// tests set it.
landResolveHook func()
+ // landInlineOff is set when the resolver did not honour a request for its rules only (an older
+ // graft-resolve): the lane then never resolves inline for the life of the process (land_inline.go).
+ landInlineOff atomic.Bool
// landFinalPassHook, when set, runs in every pass of the final pass of a land between its
// pre-resolution and its lane, with the number of the pass; only tests set it.
landFinalPassHook func(pass int)
diff --git a/internal/graft/resolver/protocol.go b/internal/graft/resolver/protocol.go
index 110bdf3..f989035 100644
--- a/internal/graft/resolver/protocol.go
+++ b/internal/graft/resolver/protocol.go
@@ -66,6 +66,11 @@ type Request struct {
// graft-resolve gives without verification: graft-resolve then gives no model's resolution
// (resolve.Resolver.resolveFile).
Capabilities []string `json:"capabilities,omitempty"`
+ // RulesOnly asks the resolver to run only its rules (the strategies whose answers are a rule's:
+ // trivial, union, rerere, a command with origin "rule") and never to call a model: the lane of
+ // the server asks it so when it resolves a member inline, within a bound of time. What the rules
+ // cannot resolve is left unresolved. A resolver that honours it says so in Response.RulesOnly.
+ RulesOnly bool `json:"rules_only,omitempty"`
}
// The capabilities of a server (Request.Capabilities).
@@ -228,6 +233,9 @@ type Response struct {
Resolver string `json:"resolver"`
Files []ResponseFile `json:"files"`
Explanation string `json:"explanation"`
+ // RulesOnly echoes a request's RulesOnly: the resolver ran only its rules. A server that asked for
+ // it and does not get it back is talking to an older resolver, and does not ask again.
+ RulesOnly bool `json:"rules_only,omitempty"`
}
// The origins of a resolved file: what made the resolution.
diff --git a/internal/graft/resolver/testdata/protocol-fields.json b/internal/graft/resolver/testdata/protocol-fields.json
index 2da7673..2f73e26 100644
--- a/internal/graft/resolver/testdata/protocol-fields.json
+++ b/internal/graft/resolver/testdata/protocol-fields.json
@@ -1,12 +1,12 @@
{
"comment": "The JSON fields of every message of the resolver protocol v1, by message. Both copies of the protocol (internal/graft/resolver and tools/graft-agents/protocol) are tested against this file, so they cannot drift: a field added to one copy fails the other's test until it is added there and here.",
- "request": ["actor", "branch", "capabilities", "commit", "files", "limits", "merge_base", "messages", "operation", "repository", "resolution", "tip", "version"],
+ "request": ["actor", "branch", "capabilities", "commit", "files", "limits", "merge_base", "messages", "operation", "repository", "resolution", "rules_only", "tip", "version"],
"repository": ["relative_path", "storage"],
"messages": ["commit", "tip"],
"file": ["base", "kind", "ours", "path", "theirs"],
"side": ["content", "mode", "oid"],
"limits": ["max_file_bytes"],
- "response": ["explanation", "files", "resolver", "version"],
+ "response": ["explanation", "files", "resolver", "rules_only", "version"],
"response_file": ["action", "content", "hold", "mode", "origin", "path", "proposal", "report"],
"error_response": ["error", "files"],
"file_outcome": ["outcome", "path", "reason"],
diff --git a/tools/graft-agents/protocol/protocol.go b/tools/graft-agents/protocol/protocol.go
index 3089e7c..5f2ae4c 100644
--- a/tools/graft-agents/protocol/protocol.go
+++ b/tools/graft-agents/protocol/protocol.go
@@ -68,6 +68,11 @@ type Request struct {
// graft-resolve gives without verification: graft-resolve then gives no model's resolution
// (resolve.Resolver.resolveFile).
Capabilities []string `json:"capabilities,omitempty"`
+ // RulesOnly asks the resolver to run only its rules (the strategies whose answers are a rule's:
+ // trivial, union, rerere, a command with origin "rule") and never to call a model: the lane of
+ // the server asks it so when it resolves a member inline, within a bound of time. What the rules
+ // cannot resolve is left unresolved. A resolver that honours it says so in Response.RulesOnly.
+ RulesOnly bool `json:"rules_only,omitempty"`
}
// The capabilities of a server (Request.Capabilities).
@@ -178,6 +183,9 @@ type Response struct {
Resolver string `json:"resolver"`
Files []ResolvedFile `json:"files"`
Explanation string `json:"explanation,omitempty"`
+ // RulesOnly echoes a request's RulesOnly: the resolver ran only its rules. A server that asked for
+ // it and does not get it back is talking to an older resolver, and does not ask again.
+ RulesOnly bool `json:"rules_only,omitempty"`
}
// ResolvedFile is the answer for one conflicted path. Content is null for
diff --git a/tools/graft-agents/resolve/resolve.go b/tools/graft-agents/resolve/resolve.go
index 206e30c..7d79b3d 100644
--- a/tools/graft-agents/resolve/resolve.go
+++ b/tools/graft-agents/resolve/resolve.go
@@ -336,8 +336,9 @@ func (r *Resolver) Resolve(ctx context.Context, req protocol.Request) (protocol.
}
resp := protocol.Response{
- Version: protocol.Version,
- Files: make([]protocol.ResolvedFile, 0, len(req.Files)),
+ Version: protocol.Version,
+ Files: make([]protocol.ResolvedFile, 0, len(req.Files)),
+ RulesOnly: req.RulesOnly,
}
var used []string
seen := map[string]bool{}
@@ -446,6 +447,10 @@ func (r *Resolver) resolveFile(ctx context.Context, req protocol.Request, f File
if !matchPaths(b.Paths, f.Path) {
continue
}
+ // The lane asked for the rules only: a model is not called, and the strategy is not a failure.
+ if req.RulesOnly && originOf(b.Strategy) == protocol.OriginModel {
+ continue
+ }
// A model's resolution is given only to a server that says it holds and verifies it. An older
// server ignores the origin, the proposal and the hold, and lands every answer it gets: the model
// is not even called (it would be paid for), and the file stays unresolved with the reason.
diff --git a/tools/graft-agents/resolve/resolve_test.go b/tools/graft-agents/resolve/resolve_test.go
index 1c7e139..5cb5c84 100644
--- a/tools/graft-agents/resolve/resolve_test.go
+++ b/tools/graft-agents/resolve/resolve_test.go
@@ -756,3 +756,42 @@ func TestAHoldIsNeverSentToAServerThatCannotHoldIt(t *testing.T) {
t.Fatalf("a server that holds must get the hold: %v %+v", err, resp.Files)
}
}
+
+// TestARequestForTheRulesOnlyNeverCallsAModel: the lane asks for the rules only when it resolves a member
+// inline. A strategy that is a model's is not called and is not a failure, what the rules resolve is
+// answered, and the answer says that the request was honoured (the server drops the answer of a
+// resolver that does not).
+func TestARequestForTheRulesOnlyNeverCallsAModel(t *testing.T) {
+ model := &proposingStrategy{fakeStrategy{fn: answer(protocol.ModeFile, "from the model\n")}}
+ rule := &fakeStrategy{fn: answer(protocol.ModeFile, "from the rule\n")}
+
+ rulesOnly := request(conflict("a.go"))
+ rulesOnly.RulesOnly = true
+
+ // The model comes first in the chain, and is skipped; the rule behind it answers.
+ r := newTestResolver(t, nil, Binding{Name: "model", Strategy: model}, Binding{Name: "rule", Strategy: rule})
+ resp, err := r.Resolve(context.Background(), rulesOnly)
+ if err != nil || len(resp.Files) != 1 || string(resp.Files[0].Content) != "from the rule\n" || resp.Files[0].Origin != protocol.OriginRule {
+ t.Fatalf("%v %+v", err, resp.Files)
+ }
+ if !resp.RulesOnly {
+ t.Fatal("the answer does not say that the request for the rules only was honoured")
+ }
+ if model.calls.Load() != 0 {
+ t.Fatalf("the model was called %d times for a request for the rules only", model.calls.Load())
+ }
+
+ // A model alone leaves the file unresolved, as a failure of the chain and not of the model.
+ r = newTestResolver(t, nil, Binding{Name: "model", Strategy: model})
+ _, err = r.Resolve(context.Background(), rulesOnly)
+ var unresolved *UnresolvedError
+ if !errors.As(err, &unresolved) || model.calls.Load() != 0 {
+ t.Fatalf("err = %v, model calls %d", err, model.calls.Load())
+ }
+
+ // An ordinary request calls the model, and does not claim the rules only.
+ resp, err = r.Resolve(context.Background(), request(conflict("a.go")))
+ if err != nil || resp.RulesOnly || model.calls.Load() != 1 || resp.Files[0].Origin != protocol.OriginModel {
+ t.Fatalf("%v rules_only=%v calls=%d %+v", err, resp.RulesOnly, model.calls.Load(), resp.Files)
+ }
+}