Skip to content

Remove side-effecting sort comparator in SkipCmd.Sort (logentry.go) #25615

Closed

Description

@fengttt

Summary

SkipCmd.Sort() in pkg/vm/engine/tae/logstore/driver/logservicedriver/logentry.go sorts by mutating a parallel array inside the comparator, which is a fragile anti-pattern we should remove.

func (s SkipCmd) Sort() {
	dsns := s.GetDSNSlice()
	psns := s.GetPSNSlice()
	sort.Slice(dsns, func(i, j int) bool {
		less := dsns[i] < dsns[j]
		if less {
			psns[i], psns[j] = psns[j], psns[i]
		}
		return less
	})
}

The intent is to keep psns reordered in lockstep with dsns. It piggybacks on sort.Slice's internal Swap (which only swaps dsns) by doing a companion swap of psns from inside the less function whenever dsns[i] < dsns[j].

Why this is a problem

A sort comparator (less) must be a pure, side-effect-free predicate. sort/slices make no guarantee about which index pairs less is invoked on, how many times, or in what order — introsort calls it during partitioning, insertion sort, and heap phases. Reordering psns on every i<j observation is not guaranteed to leave psns a valid permutation matching the final dsns order; it only happens to work for the current algorithm/input shapes.

This also blocks a straightforward migration to slices.SortFunc (which is why it was the single site left untouched in #25616 — the slices package calls the comparator with a different pairing/count and would corrupt the parallel array).

Suggested fix

Sort an index permutation with a pure comparator, then apply it to both slices:

func (s SkipCmd) Sort() {
	dsns := s.GetDSNSlice()
	psns := s.GetPSNSlice()
	idx := make([]int, len(dsns))
	for i := range idx {
		idx[i] = i
	}
	slices.SortFunc(idx, func(a, b int) int { return cmp.Compare(dsns[a], dsns[b]) })
	// apply permutation to dsns and psns (in place via cycle-follow, or into temp buffers)
}

(or gather into {dsn, psn} pairs, sort the pairs, scatter back.)

Scope

This is the only remaining side-effecting sort comparator after the sort.Slice -> slices escape-analysis pass (#25616). Worth fixing both for correctness robustness and to complete the slices migration.

Metadata

Metadata

Assignees

Labels

severity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions