package beads
import (
"context"
"fmt"
"net/url"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"sourcecraft.dev/bigbes/sr-ht-dolt/browse"
)
// --- a session that clips the way the store does -----------------------------
// clippingSession is a BrowseSession that honours offset/limit and reports the
// table's true row count, which is what a real read at limit=Max does: the
// first Max rows, and a Total that says the rest exists.
//
// The clip is performed by the seam rather than written into a fixture by hand.
// A page whose Total simply disagrees with its own Rows would let a test assert
// the flag while never producing the situation the flag is about — and the tail
// row, which is the whole point of the "not in what was read" case, has to be
// genuinely absent from the rows handed to the projection.
type clippingSession struct {
rowsByTable map[string]*browse.RowPage
}
func (s *clippingSession) Rows(_ context.Context, _, table string, offset, limit int) (*browse.RowPage, error) {
p, ok := s.rowsByTable[table]
if !ok {
return nil, fmt.Errorf("%w: %s", browse.ErrTableNotFound, table)
}
total := len(p.Rows)
lo := offset
if lo > total {
lo = total
}
hi := total
if limit > 0 && lo+limit < hi {
hi = lo + limit
}
return &browse.RowPage{Columns: p.Columns, Rows: p.Rows[lo:hi], Offset: lo, Total: total}, nil
}
// --- fixtures past the cap ---------------------------------------------------
// manyIssues builds n issue rows, ids i-0000… in order, cycling through the
// three status categories. With n > Max the ids from index Max on are the tail
// a capped read never sees.
func manyIssues(n int) *browse.RowPage {
statuses := []string{"open", "in_progress", "closed"}
rows := make([][]string, 0, n)
for i := 0; i < n; i++ {
rows = append(rows, []string{
issueID(i),
fmt.Sprintf("Issue %d", i),
statuses[i%len(statuses)],
"1",
"task",
"alice",
fmt.Sprintf("2024-01-01 00:00:%02d", i%60),
"0",
})
}
return &browse.RowPage{
Columns: []string{"id", "title", "status", "priority", "issue_type", "assignee", "created_at", "is_blocked"},
Rows: rows,
Total: n,
}
}
func issueID(i int) string { return fmt.Sprintf("i-%04d", i) }
func statusRows() *browse.RowPage {
return &browse.RowPage{
Columns: []string{"name", "category"},
Rows: [][]string{
{"open", "open"},
{"in_progress", "in_progress"},
{"closed", "closed"},
},
Total: 3,
}
}
// bigTracker is a tracker of Max+5 issues: five of them exist only past the cap.
// Every other table stays small, so a flag raised over this fixture can only
// have come from the issues read.
//
// Two issues carry milestone:m1 — i-0003, which a capped read sees, and
// i-2003, which it does not. The rollup over a clipped read therefore reports
// half a milestone, which is the arithmetic this fixture is here to catch.
func bigTracker() *clippingSession {
return &clippingSession{rowsByTable: map[string]*browse.RowPage{
"issues": manyIssues(Max + 5),
"dependencies": {
Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
Rows: [][]string{{"d1", "i-0007", "i-0001", "blocks"}},
Total: 1,
},
"labels": {
Columns: []string{"issue_id", "label"},
Rows: [][]string{
{"i-0003", "milestone:m1"},
{"i-2003", "milestone:m1"},
{"i-0007", "backend"},
},
Total: 3,
},
"custom_statuses": statusRows(),
}}
}
// smallTrackerWith is three issues and no clip anywhere, plus whatever extra
// tables a test wants to oversize. It isolates the clip to one optional table.
func smallTrackerWith(extra map[string]*browse.RowPage) *clippingSession {
tables := map[string]*browse.RowPage{
"issues": manyIssues(3),
"dependencies": {
Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
Rows: [][]string{{"d1", "i-0001", "i-0000", "blocks"}},
Total: 1,
},
"custom_statuses": statusRows(),
}
for name, page := range extra {
tables[name] = page
}
return &clippingSession{rowsByTable: tables}
}
// manyComments builds n comment rows, all on i-0000.
func manyComments(n int) *browse.RowPage {
rows := make([][]string, 0, n)
for i := 0; i < n; i++ {
rows = append(rows, []string{"i-0000", "alice", fmt.Sprintf("comment %d", i), "2024-01-05 00:00:00"})
}
return &browse.RowPage{
Columns: []string{"issue_id", "author", "text", "created_at"},
Rows: rows,
Total: n,
}
}
// manyLabels builds n label rows, all on i-0000, named label-0000 upwards. A
// read that stops at Max leaves the rest off every card and out of the board's
// label filter.
func manyLabels(n int) *browse.RowPage {
rows := make([][]string, 0, n)
for i := 0; i < n; i++ {
rows = append(rows, []string{"i-0000", fmt.Sprintf("label-%04d", i)})
}
return &browse.RowPage{Columns: []string{"issue_id", "label"}, Rows: rows, Total: n}
}
// manyStatuses builds n custom_statuses rows: the three real categories first,
// then filler. The real ones lead so the lanes still bucket correctly and the
// only thing under test is that the clip is reported.
func manyStatuses(n int) *browse.RowPage {
rows := [][]string{{"open", "open"}, {"in_progress", "in_progress"}, {"closed", "closed"}}
for i := len(rows); i < n; i++ {
rows = append(rows, []string{fmt.Sprintf("status-%04d", i), "open"})
}
return &browse.RowPage{Columns: []string{"name", "category"}, Rows: rows, Total: len(rows)}
}
func detail(t *testing.T, sess BrowseSession, id string) *Data {
t.Helper()
d, err := Build(context.Background(), sess, "main", url.Values{"issue": {id}})
require.NoError(t, err)
require.Contains(t, []string{"detail", "epic"}, d.Mode)
return d
}
// --- the detail branch -------------------------------------------------------
func TestDetailReportsAClippedIssuesRead(t *testing.T) {
d := detail(t, bigTracker(), "i-0007")
require.NotNil(t, d.Issue, "i-0007 is inside the first Max rows")
assert.Equal(t, "i-0007", d.Issue.ID)
assert.True(t, d.Truncated, "the issues table exceeded Max")
assert.True(t, d.IssuesClipped())
assert.Equal(t, Max+5, d.ShownOf, "the tracker's true issue count, not the number read")
assert.False(t, d.Missing())
assert.False(t, d.MissingBeyondCap())
}
func TestDetailIssueInTheTailIsNotAbsence(t *testing.T) {
sess := bigTracker()
d := detail(t, sess, "i-2003")
// The issue exists in the tracker...
rows := sess.rowsByTable["issues"].Rows
assert.Equal(t, "i-2003", rows[2003][0])
// ...but not in the rows this projection read, and it says so.
assert.Nil(t, d.Issue)
assert.True(t, d.Missing())
assert.True(t, d.MissingBeyondCap(), "the read was clipped, so absence is not established")
assert.True(t, d.IssuesClipped())
assert.Equal(t, Max+5, d.ShownOf)
}
func TestDetailAbsentIssueOnACompleteReadIsAbsence(t *testing.T) {
d := detail(t, beadsFixture(), "i-nope")
assert.Nil(t, d.Issue)
assert.True(t, d.Missing())
assert.False(t, d.MissingBeyondCap(), "nothing was clipped, so the id genuinely does not exist")
assert.False(t, d.Truncated)
assert.False(t, d.IssuesClipped())
assert.Equal(t, 4, d.ShownOf)
}
func TestDetailReportsAClippedCommentsRead(t *testing.T) {
d := detail(t, smallTrackerWith(map[string]*browse.RowPage{
"comments": manyComments(Max + 3),
}), "i-0000")
require.NotNil(t, d.Issue)
assert.Len(t, d.Comments, Max, "the thread is the comments that were read")
assert.True(t, d.Truncated, "the comments table was clipped, so the thread is partial")
assert.False(t, d.IssuesClipped(), "the issue set itself is complete")
assert.Equal(t, 3, d.ShownOf)
}
func TestDetailReportsAClippedLabelsRead(t *testing.T) {
labels := make([][]string, 0, Max+2)
for i := 0; i < Max+2; i++ {
labels = append(labels, []string{"i-0002", fmt.Sprintf("label-%04d", i)})
}
sess := smallTrackerWith(map[string]*browse.RowPage{
"labels": {Columns: []string{"issue_id", "label"}, Rows: labels, Total: len(labels)},
})
d := detail(t, sess, "i-0000")
require.NotNil(t, d.Issue)
assert.True(t, d.Truncated, "labels feed the detail pane, so a clipped labels read is partial too")
assert.False(t, d.IssuesClipped())
}
// --- the board's flag is what it always was ----------------------------------
// The flag and its number are what they were before the board learned to name
// the tables it draws from: Truncated is still the issues/dependencies pair the
// lanes are bucketed from, and ShownOf is still the issues table's total. The
// per-table list is a second, wider fact carried beside them (Data.Clipped,
// exercised below), never a new meaning for these two — mcpsrv's list_issues
// reads them as they are.
func TestBoardTruncationFlagIsUnchanged(t *testing.T) {
t.Run("clipped issues", func(t *testing.T) {
d, err := Build(context.Background(), bigTracker(), "main", url.Values{})
require.NoError(t, err)
require.Equal(t, "board", d.Mode)
assert.True(t, d.Truncated)
assert.Equal(t, Max+5, d.ShownOf)
assert.Equal(t, Max, d.Counts.Total, "the board holds the rows that were read")
assert.False(t, d.Missing(), "a board is never a miss")
})
t.Run("clipped dependencies", func(t *testing.T) {
deps := make([][]string, 0, Max+1)
for i := 0; i < Max+1; i++ {
deps = append(deps, []string{fmt.Sprintf("d%d", i), "i-0001", "i-0000", "blocks"})
}
sess := smallTrackerWith(map[string]*browse.RowPage{
"dependencies": {
Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
Rows: deps,
Total: len(deps),
},
})
d, err := Build(context.Background(), sess, "main", url.Values{})
require.NoError(t, err)
assert.True(t, d.Truncated, "dependencies is one of the two tables the board buckets from")
assert.False(t, d.IssuesClipped(), "and Truncated is not the same fact as a clipped issue set")
assert.Equal(t, 3, d.ShownOf)
})
t.Run("a clip in a table the board does not read", func(t *testing.T) {
// The board's flag has always named issues and dependencies, and comments is
// not a table the board reads at all: the thread belongs to one issue's
// detail pane. Neither the flag nor the per-table list may mention it —
// the board reports the tables it draws from, and no others.
d, err := Build(context.Background(), smallTrackerWith(map[string]*browse.RowPage{
"comments": manyComments(Max + 3),
}), "main", url.Values{})
require.NoError(t, err)
assert.False(t, d.Truncated)
assert.False(t, d.IssuesClipped())
assert.Empty(t, clippedNames(d), "the board never read comments, so it has nothing to say about it")
})
t.Run("labels and custom_statuses do not flip the flag", func(t *testing.T) {
// They are reported — see TestBoardReportsEveryClippedTableItDrawsFrom —
// but through Clipped, not by widening Truncated. A flag that meant four
// different things would take the count line's meaning with it: neither of
// these tables changes how many issues were read.
d, err := Build(context.Background(), smallTrackerWith(map[string]*browse.RowPage{
"labels": manyLabels(Max + 2),
"custom_statuses": manyStatuses(Max + 1),
}), "main", url.Values{})
require.NoError(t, err)
assert.False(t, d.Truncated, "the issues and dependencies reads were both whole")
assert.False(t, d.IssuesClipped())
assert.Equal(t, 3, d.ShownOf)
})
}
// --- the board names every table it draws from -------------------------------
// clippedNames is the board's clip list as table names, in the order it reports
// them.
func clippedNames(d *Data) []string {
out := make([]string, 0, len(d.Clipped))
for _, c := range d.Clipped {
out = append(out, c.Table)
}
return out
}
// clipFor returns the entry the board reported for a table, failing the test
// when it reported none.
func clipFor(t *testing.T, d *Data, table string) ClippedTable {
t.Helper()
for _, c := range d.Clipped {
if c.Table == table {
return c
}
}
require.FailNowf(t, "no entry", "the board says nothing about a clipped %s table; it reported %v", table, clippedNames(d))
return ClippedTable{}
}
// A clipped labels table degrades every card on the board — the pills go
// missing and the label filter silently offers only the labels that were read —
// without moving a single count, which is exactly why one flag could not carry
// it. Each entry names its table, both numbers, and what the board lost.
func TestBoardReportsEveryClippedTableItDrawsFrom(t *testing.T) {
t.Run("clipped labels", func(t *testing.T) {
d, err := Build(context.Background(), smallTrackerWith(map[string]*browse.RowPage{
"labels": manyLabels(Max + 2),
}), "main", url.Values{})
require.NoError(t, err)
require.Equal(t, []string{"labels"}, clippedNames(d))
c := clipFor(t, d, "labels")
assert.Equal(t, Max, c.Shown, "the rows that were read")
assert.Equal(t, Max+2, c.Total, "the rows the table holds")
assert.NotEmpty(t, c.Effect, "a table named without a cost is a bare warning")
// The degradation the entry is about, on the board itself: the labels past
// the cap are on neither a card nor the filter's list.
assert.NotContains(t, d.FilterOpts.Labels, fmt.Sprintf("label-%04d", Max+1),
"the filter offers only the labels that were read")
})
t.Run("clipped custom_statuses", func(t *testing.T) {
d, err := Build(context.Background(), smallTrackerWith(map[string]*browse.RowPage{
"custom_statuses": manyStatuses(Max + 1),
}), "main", url.Values{})
require.NoError(t, err)
require.Equal(t, []string{"custom_statuses"}, clippedNames(d))
assert.Equal(t, Max+1, clipFor(t, d, "custom_statuses").Total)
assert.False(t, d.Truncated, "and it is reported without touching the flag")
})
t.Run("clipped issues", func(t *testing.T) {
d, err := Build(context.Background(), bigTracker(), "main", url.Values{})
require.NoError(t, err)
require.Equal(t, []string{"issues"}, clippedNames(d))
c := clipFor(t, d, "issues")
assert.Equal(t, Max, c.Shown)
assert.Equal(t, Max+5, c.Total)
assert.Equal(t, d.ShownOf, c.Total, "the same number the count line has always shown")
})
t.Run("clipped dependencies", func(t *testing.T) {
deps := make([][]string, 0, Max+1)
for i := 0; i < Max+1; i++ {
deps = append(deps, []string{fmt.Sprintf("d%d", i), "i-0001", "i-0000", "blocks"})
}
d, err := Build(context.Background(), smallTrackerWith(map[string]*browse.RowPage{
"dependencies": {
Columns: []string{"id", "issue_id", "depends_on_issue_id", "type"},
Rows: deps,
Total: len(deps),
},
}), "main", url.Values{})
require.NoError(t, err)
require.Equal(t, []string{"dependencies"}, clippedNames(d))
assert.Equal(t, Max+1, clipFor(t, d, "dependencies").Total)
})
t.Run("several at once, in read order", func(t *testing.T) {
sess := smallTrackerWith(map[string]*browse.RowPage{
"issues": manyIssues(Max + 5),
"labels": manyLabels(Max + 2),
"custom_statuses": manyStatuses(Max + 1),
})
d, err := Build(context.Background(), sess, "main", url.Values{})
require.NoError(t, err)
assert.Equal(t, []string{"issues", "labels", "custom_statuses"}, clippedNames(d),
"read order, so the list is the same on every request")
})
t.Run("a complete read", func(t *testing.T) {
d, err := Build(context.Background(), beadsFixture(), "main", url.Values{})
require.NoError(t, err)
assert.Empty(t, d.Clipped, "nothing was clipped, so the board has nothing to report")
assert.False(t, d.Truncated)
})
t.Run("the detail pane keeps its one line", func(t *testing.T) {
// Clipped is the board's answer. A detail pane reads a different set of
// tables for a single issue and says its one sentence from Truncated;
// giving it a board's list would be a second, board-shaped story about a
// page that never drew a lane.
d := detail(t, bigTracker(), "i-0007")
assert.True(t, d.Truncated)
assert.Empty(t, d.Clipped)
})
}
// --- the milestone rollup ----------------------------------------------------
func TestMilestonesReportAClippedRead(t *testing.T) {
v, err := BuildMilestones(context.Background(), bigTracker(), "main")
require.NoError(t, err)
assert.True(t, v.Truncated, "the rollup below is arithmetic over a partial read")
assert.True(t, v.IssuesClipped())
assert.Equal(t, Max, v.Total, "issues read")
assert.Equal(t, Max+5, v.ShownOf, "issues that exist")
require.Len(t, v.Milestones, 1)
assert.Equal(t, 1, v.Milestones[0].Total,
"m1's other member is i-2003, which sits past the cap — the count is short and the view says why")
}
func TestMilestonesOnACompleteReadReportNoClip(t *testing.T) {
v, err := BuildMilestones(context.Background(), milestoneFixture(), "main")
require.NoError(t, err)
assert.False(t, v.Truncated)
assert.False(t, v.IssuesClipped())
assert.Equal(t, 6, v.Total)
assert.Equal(t, v.Total, v.ShownOf, "nothing was left behind, so the two agree")
}
func TestMilestonesReportAClippedLabelsRead(t *testing.T) {
labels := make([][]string, 0, Max+2)
labels = append(labels, []string{"i-0000", "milestone:m1"})
for i := 0; i < Max+1; i++ {
labels = append(labels, []string{"i-0002", fmt.Sprintf("label-%04d", i)})
}
sess := smallTrackerWith(map[string]*browse.RowPage{
"labels": {Columns: []string{"issue_id", "label"}, Rows: labels, Total: len(labels)},
})
v, err := BuildMilestones(context.Background(), sess, "main")
require.NoError(t, err)
assert.True(t, v.Truncated, "membership itself was read partially")
assert.False(t, v.IssuesClipped(), "though every issue was read")
assert.Equal(t, 3, v.Total)
assert.Equal(t, 3, v.ShownOf)
}