Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-9654 perf(properties): compute usage_count in one pass and take it off the hot path (#10980)
Multica Evefb824cd9f7ff
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 76774fb9ba..1184ada364 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -5149,11 +5149,20 @@ export class ApiClient {}// Custom issue properties- async listProperties(includeArchived = false): Promise<ListPropertiesResponse> {- const suffix = includeArchived ? "?include_archived=true" : "";+ /**+ * Usage counts cost the server a pass over the workspace's issues, so they+ * are opt-in: without `includeUsage` every `usage_count` comes back 0.+ */+ async listProperties(+ includeArchived = false,+ { includeUsage = false }: { includeUsage?: boolean } = {},+ ): Promise<ListPropertiesResponse> {+ const params = new URLSearchParams();+ if (includeArchived) params.set("include_archived", "true");+ if (!includeUsage) params.set("include_usage", "false");let raw: unknown;try {- raw = await this.fetch<unknown>(`/api/properties${suffix}`);+ raw = await this.fetch<unknown>(`/api/properties?${params}`);} catch (error) {// A backend predating custom properties 404s here (e.g. after a// server-only rollback). Treat it as an empty catalog: the propertydiff --git a/packages/core/properties/index.ts b/packages/core/properties/index.tsindex 1354c1797f..6148ac9b11 100644--- a/packages/core/properties/index.ts+++ b/packages/core/properties/index.ts@@ -1,4 +1,4 @@-export { propertyKeys, propertyListOptions } from "./queries";+export { propertyKeys, propertyListOptions, propertyUsageListOptions } from "./queries";export {useCreateProperty,useUpdateProperty,diff --git a/packages/core/properties/mutations.test.tsx b/packages/core/properties/mutations.test.tsxindex 8f034fd30b..38cf33d233 100644--- a/packages/core/properties/mutations.test.tsx+++ b/packages/core/properties/mutations.test.tsx@@ -11,6 +11,7 @@ import type { ApiClient } from "../api/client";import type { Issue, IssuePropertiesResponse } from "../types";import { issueKeys } from "../issues/queries";import { useSetIssueProperty } from "./mutations";+import { propertyKeys } from "./queries";vi.mock("../hooks", () => ({ useWorkspaceId: () => "ws-1" }));@@ -173,4 +174,29 @@ describe("useSetIssueProperty", () => {);qc.clear();});++ // Every issue surface observes the plain catalog; refetching it on each+ // value write made bulk edits fan out into workspace-wide usage scans.+ it("invalidates only the counted catalog when a value write settles", async () => {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const empty = { properties: [], total: 0 };+ qc.setQueryData(propertyKeys.list("ws-1"), empty);+ qc.setQueryData(propertyKeys.list("ws-1", true), empty);+ qc.setQueryData(propertyKeys.withUsage("ws-1"), empty);+ setApiInstance({+ setIssueProperty: vi.fn().mockResolvedValue({ properties: { estimate: 3 } }),+ } as unknown as ApiClient);++ const { result } = renderHook(() => useSetIssueProperty(), { wrapper: wrapper(qc) });+ await act(async () => {+ await result.current.mutateAsync({ issueId: issue.id, propertyId: "estimate", value: 3 });+ });++ await waitFor(() =>+ expect(qc.getQueryState(propertyKeys.withUsage("ws-1"))?.isInvalidated).toBe(true),+ );+ expect(qc.getQueryState(propertyKeys.list("ws-1"))?.isInvalidated).toBe(false);+ expect(qc.getQueryState(propertyKeys.list("ws-1", true))?.isInvalidated).toBe(false);+ qc.clear();+ });});diff --git a/packages/core/properties/mutations.ts b/packages/core/properties/mutations.tsindex cc7afbbfb0..3cabe26b3c 100644--- a/packages/core/properties/mutations.ts+++ b/packages/core/properties/mutations.ts@@ -198,7 +198,7 @@ function rollbackSingleKey(function settleIssuePropertyCaches(qc: ReturnType<typeof useQueryClient>, wsId: string, issueId: string) {if (qc.isMutating({ mutationKey: ["issue-properties", wsId] }) > 1) return;qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });- qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: propertyKeys.withUsage(wsId) });// Server-filtered/-sorted windows must refetch: the write may have moved// this issue across pages or reordered it (onIssuePropertiesChanged// already fires this for the WS path; local mutations need it on settlediff --git a/packages/core/properties/queries.ts b/packages/core/properties/queries.tsindex 2e42b24c05..e2d296d39f 100644--- a/packages/core/properties/queries.ts+++ b/packages/core/properties/queries.ts@@ -5,8 +5,13 @@ export const propertyKeys = {all: (wsId: string) => ["properties", wsId] as const,list: (wsId: string, includeArchived = false) =>[...propertyKeys.all(wsId), "list", includeArchived] as const,+ /** The settings catalog with per-definition usage counts. Value writes only+ * move counts, so they invalidate this key and leave `list` alone. */+ withUsage: (wsId: string) => [...propertyKeys.all(wsId), "with-usage"] as const,};+/** The definition catalog. `usage_count` is always 0 here; use+ * `propertyUsageListOptions` where counts are shown. */export function propertyListOptions(wsId: string, includeArchived = false) {return queryOptions({queryKey: propertyKeys.list(wsId, includeArchived),@@ -14,3 +19,12 @@ export function propertyListOptions(wsId: string, includeArchived = false) {select: (data) => data.properties,});}++/** Every definition, archived included, with real usage counts. */+export function propertyUsageListOptions(wsId: string) {+ return queryOptions({+ queryKey: propertyKeys.withUsage(wsId),+ queryFn: () => api.listProperties(true, { includeUsage: true }),+ select: (data) => data.properties,+ });+}diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex e656bac7f1..3da5e0f947 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1368,10 +1368,9 @@ export function useRealtimeSync(if (wsId) {onIssuePropertiesChanged(qc, wsId, issue_id, properties ?? {}, issue_revision);scheduleProjectActivityRefresh(wsId);- // The catalog embeds per-definition usage counts; every value- // set/unset shifts them. The list is tiny, so a refetch beats- // trying to patch counts client-side.- qc.invalidateQueries({ queryKey: propertyKeys.all(wsId) });+ // Value set/unset shifts usage counts only; the plain catalog is+ // unchanged. Only the settings view observes the counted list.+ qc.invalidateQueries({ queryKey: propertyKeys.withUsage(wsId) });}});diff --git a/packages/views/settings/components/properties-tab.test.tsx b/packages/views/settings/components/properties-tab.test.tsxindex c09af156be..9611e1d356 100644--- a/packages/views/settings/components/properties-tab.test.tsx+++ b/packages/views/settings/components/properties-tab.test.tsx@@ -41,7 +41,7 @@ vi.mock("@multica/core/workspace/queries", () => ({}));vi.mock("@multica/core/properties", () => ({- propertyListOptions: (wsId: string) => ({ queryKey: ["properties", wsId] }),+ propertyUsageListOptions: (wsId: string) => ({ queryKey: ["properties", wsId, "with-usage"] }),useCreateProperty: () => ({ mutate: vi.fn(), isPending: false }),useUpdateProperty: () => ({ mutate: vi.fn(), isPending: false }),}));diff --git a/packages/views/settings/components/properties-tab.tsx b/packages/views/settings/components/properties-tab.tsxindex 6b0b82f1f2..3b0cc4df4d 100644--- a/packages/views/settings/components/properties-tab.tsx+++ b/packages/views/settings/components/properties-tab.tsx@@ -18,7 +18,7 @@ import { useAuthStore } from "@multica/core/auth";import { useWorkspaceId } from "@multica/core/hooks";import { memberListOptions } from "@multica/core/workspace/queries";import {- propertyListOptions,+ propertyUsageListOptions,useCreateProperty,useUpdateProperty,} from "@multica/core/properties";@@ -127,7 +127,7 @@ export function PropertiesTab() {const currentMember = members.find((m) => m.user_id === user?.id) ?? null;const canManage = currentMember?.role === "owner" || currentMember?.role === "admin";- const { data: properties = [], isLoading } = useQuery(propertyListOptions(wsId, true));+ const { data: properties = [], isLoading } = useQuery(propertyUsageListOptions(wsId));const update = useUpdateProperty();const activeCount = useMemo(diff --git a/server/cmd/multica/cmd_property.go b/server/cmd/multica/cmd_property.goindex 5d978813a8..0e8eb70ca1 100644--- a/server/cmd/multica/cmd_property.go+++ b/server/cmd/multica/cmd_property.go@@ -206,12 +206,23 @@ func init() {// fetchProperties loads the full definition catalog (including archived — the// callers that must exclude archived filter locally, and value resolution for-// display needs archived definitions too).+// display needs archived definitions too). usage_count is left at 0: counting+// costs a pass over the workspace's issues, which name resolution does not+// need. Commands that print usage_count use fetchPropertiesWithUsage.func fetchProperties(ctx context.Context, client *cli.APIClient) ([]propertyDTO, error) {+ return fetchPropertyCatalog(ctx, client, "/api/properties?include_archived=true&include_usage=false")+}++// fetchPropertiesWithUsage is fetchProperties with real usage counts.+func fetchPropertiesWithUsage(ctx context.Context, client *cli.APIClient) ([]propertyDTO, error) {+ return fetchPropertyCatalog(ctx, client, "/api/properties?include_archived=true")+}++func fetchPropertyCatalog(ctx context.Context, client *cli.APIClient, path string) ([]propertyDTO, error) {var result struct {Properties []propertyDTO `json:"properties"`}- if err := client.GetJSON(ctx, "/api/properties?include_archived=true", &result); err != nil {+ if err := client.GetJSON(ctx, path, &result); err != nil {return nil, fmt.Errorf("list properties: %w", err)}return result.Properties, nil@@ -318,7 +329,7 @@ func runPropertyGet(cmd *cobra.Command, args []string) error {ctx, cancel := cli.APIContext(context.Background())defer cancel()- properties, err := fetchProperties(ctx, client)+ properties, err := fetchPropertiesWithUsage(ctx, client)if err != nil {return err}diff --git a/server/cmd/multica/cmd_property_test.go b/server/cmd/multica/cmd_property_test.goindex 74f9671aad..4d55e20b1a 100644--- a/server/cmd/multica/cmd_property_test.go+++ b/server/cmd/multica/cmd_property_test.go@@ -2,6 +2,8 @@ package mainimport ("encoding/json"+ "net/http"+ "net/http/httptest""reflect""testing"@@ -123,3 +125,42 @@ func TestRunIssuePropertySetSharesMembersRequest(t *testing.T) {t.Errorf("rows = %#v, want %#v", rows, want)}}++// `property get` prints usage_count, so it must not use the catalog fetch+// that opts out of counting (the server returns 0 under include_usage=false).+func TestRunPropertyGetKeepsUsageCount(t *testing.T) {+ const propID = "11111111-1111-1111-1111-111111111111"+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/properties" {+ http.NotFound(w, r)+ return+ }+ usage := int64(2)+ if r.URL.Query().Get("include_usage") == "false" {+ usage = 0+ }+ _ = json.NewEncoder(w).Encode(map[string]any{"properties": []propertyDTO{+ {ID: propID, Name: "Impact", Type: "text", UsageCount: usage},+ }})+ }))+ t.Cleanup(srv.Close)+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")++ for _, ref := range []string{"Impact", propID} {+ cmd := &cobra.Command{Use: "get"}+ cmd.Flags().String("output", "json", "")+ out, err := captureStdout(t, func() error { return runPropertyGet(cmd, []string{ref}) })+ if err != nil {+ t.Fatalf("runPropertyGet(%q): %v", ref, err)+ }+ var got propertyDTO+ if err := json.Unmarshal([]byte(out), &got); err != nil {+ t.Fatalf("unmarshal output: %v\n%s", err, out)+ }+ if got.UsageCount != 2 {+ t.Errorf("runPropertyGet(%q) usage_count = %d, want 2", ref, got.UsageCount)+ }+ }+}diff --git a/server/internal/handler/property.go b/server/internal/handler/property.goindex db298682cb..00f7076608 100644--- a/server/internal/handler/property.go+++ b/server/internal/handler/property.go@@ -1,6 +1,7 @@package handlerimport (+ "context""encoding/json""errors""fmt"@@ -144,22 +145,6 @@ func propertyToResponse(p db.IssueProperty, usageCount int64) PropertyResponse {return resp}-func propertyListRowToResponse(row db.ListIssuePropertiesRow) PropertyResponse {- return propertyToResponse(db.IssueProperty{- ID: row.ID,- WorkspaceID: row.WorkspaceID,- Name: row.Name,- Type: row.Type,- Description: row.Description,- Icon: row.Icon,- Config: row.Config,- Position: row.Position,- ArchivedAt: row.ArchivedAt,- CreatedAt: row.CreatedAt,- UpdatedAt: row.UpdatedAt,- }, row.UsageCount)-}-type CreatePropertyRequest struct {Name string `json:"name"`Type string `json:"type"`@@ -408,7 +393,7 @@ func (h *Handler) ListProperties(w http.ResponseWriter, r *http.Request) {return}includeArchived := r.URL.Query().Get("include_archived") == "true"- rows, err := h.Queries.ListIssueProperties(r.Context(), db.ListIssuePropertiesParams{+ listed, err := h.Queries.ListIssueProperties(r.Context(), db.ListIssuePropertiesParams{WorkspaceID: wsUUID,IncludeArchived: includeArchived,})@@ -417,13 +402,99 @@ func (h *Handler) ListProperties(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list properties")return}- resp := make([]PropertyResponse, len(rows))- for i, row := range rows {- resp[i] = propertyListRowToResponse(row)+ // usage_count costs a pass over the workspace's property-carrying issues,+ // so callers that only need the catalog (issue surfaces, CLI name+ // resolution, realtime refetches) send include_usage=false and get 0.+ // Anything else keeps the counts, which is what older clients expect.+ var usage map[string]int64+ if r.URL.Query().Get("include_usage") != "false" {+ if usage, err = h.countPropertyUsage(r.Context(), wsUUID, listed); err != nil {+ slog.Warn("count property usage failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to list properties")+ return+ }+ }+ resp := make([]PropertyResponse, len(listed))+ for i, p := range listed {+ resp[i] = propertyToResponse(p, usage[uuidToString(p.ID)])}writeJSON(w, http.StatusOK, map[string]any{"properties": resp, "total": len(resp)})}+// propertyUsageKeysPerScan caps how many definitions one usage scan counts:+// each becomes an output column, and PostgreSQL allows at most 1664.+const propertyUsageKeysPerScan = 1000++// countPropertyUsage returns, keyed by property id, how many of the+// workspace's issues carry a value for each of the given definitions.+func (h *Handler) countPropertyUsage(ctx context.Context, workspaceID pgtype.UUID, props []db.IssueProperty) (map[string]int64, error) {+ usage := make(map[string]int64, len(props))+ for start := 0; start < len(props); start += propertyUsageKeysPerScan {+ chunk := props[start:min(start+propertyUsageKeysPerScan, len(props))]+ query, args := propertyUsageQuery(workspaceID, chunk)+ counts := make([]int64, len(chunk))+ dest := make([]any, len(chunk))+ for i := range counts {+ dest[i] = &counts[i]+ }+ if err := h.DB.QueryRow(ctx, query, args...).Scan(dest...); err != nil {+ return nil, err+ }+ for i, p := range chunk {+ usage[uuidToString(p.ID)] = counts[i]+ }+ }+ return usage, nil+}++// propertyUsageQuery counts, in one pass over the workspace's issues, how+// many carry each definition's key: one COUNT(*) FILTER column per+// definition, in order.+//+// The shape is deliberate:+// - Not a per-definition `properties ? id` subquery: idx_issue_properties_gin+// is jsonb_path_ops, which cannot serve `?`, so each definition re-read+// every issue in the workspace.+// - No row per (issue, key), as jsonb_object_keys or an unnest join would+// produce: when most issues carry the counted keys, building and grouping+// those rows costs more than the per-definition scans did.+// - The scan filters on workspace_id alone, inside an OFFSET 0 subquery,+// and every JSON check runs above it. A JSON condition in the same scan+// can be checked before workspace_id (PostgreSQL appends the equality it+// derives for workspace_id after the other filters). A sequential scan+// then reads every other workspace's bags too, which costs most when+// other workspaces store large ones.+// - `properties || '{}'` detoasts each bag once for all the `?` checks.+// Bags past the TOAST threshold would otherwise be fetched and+// decompressed again for every `?`. A single definition skips it: its+// one `?` reads the bag once already.+func propertyUsageQuery(workspaceID pgtype.UUID, props []db.IssueProperty) (string, []any) {+ if len(props) == 1 {+ return `SELECT COUNT(*) FILTER (WHERE s.properties ? $2::text)+FROM (+ SELECT i.properties+ FROM issue i+ WHERE i.workspace_id = $1::uuid+ OFFSET 0+) s`, []any{workspaceID, uuidToString(props[0].ID)}+ }+ args := make([]any, 0, len(props)+1)+ args = append(args, workspaceID)+ columns := make([]string, len(props))+ for i, p := range props {+ args = append(args, uuidToString(p.ID))+ columns[i] = fmt.Sprintf("COUNT(*) FILTER (WHERE s.properties ? $%d::text)", len(args))+ }+ return fmt.Sprintf(`SELECT %s+FROM (+ SELECT i.properties || '{}'::jsonb AS properties+ FROM issue i+ WHERE i.workspace_id = $1::uuid+ OFFSET 0+) s+WHERE s.properties <> '{}'::jsonb`, strings.Join(columns, ", ")), args+}+func (h *Handler) GetProperty(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "property id")diff --git a/server/internal/handler/property_test.go b/server/internal/handler/property_test.goindex 3d65229236..024029b716 100644--- a/server/internal/handler/property_test.go+++ b/server/internal/handler/property_test.go@@ -2,18 +2,22 @@ package handlerimport ("context"+ "crypto/rand"+ "encoding/hex""encoding/json""fmt""math""net/http""net/http/httptest""net/url"+ "regexp""sort""strings""testing""github.com/go-chi/chi/v5""github.com/google/uuid"+ "github.com/jackc/pgx/v5""github.com/multica-ai/multica/server/internal/issueproperty""github.com/multica-ai/multica/server/internal/testutil"@@ -190,6 +194,425 @@ func TestPropertyDefinitionCRUD(t *testing.T) {}}+// usage_count is a per-definition census of issues carrying a value; the+// include_usage=false catalog skips it but must list the same definitions.+func TestListPropertiesUsageCount(t *testing.T) {+ suffix := uuid.NewString()[:8]+ propA := createTestProperty(t, map[string]any{"name": "Usage A " + suffix, "type": "text"})+ propB := createTestProperty(t, map[string]any{"name": "Usage B " + suffix, "type": "text"})+ unused := createTestProperty(t, map[string]any{"name": "Usage C " + suffix, "type": "text"})++ both := createPropertyTestIssue(t, "usage both "+suffix)+ onlyA := createPropertyTestIssue(t, "usage only A "+suffix)+ createPropertyTestIssue(t, "usage none "+suffix)+ for _, set := range []struct{ issue, prop string }{{both, propA.ID}, {both, propB.ID}, {onlyA, propA.ID}} {+ if w := setIssuePropertyRaw(t, set.issue, set.prop, "v"); w.Code != http.StatusOK {+ t.Fatalf("SetIssueProperty: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ }++ // Archived definitions keep their count in the include_archived list.+ w := httptest.NewRecorder()+ req := withURLParam(newRequest("PATCH", "/api/properties/"+propB.ID, map[string]any{"archived": true}), "id", propB.ID)+ testHandler.UpdateProperty(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("archive: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ counts := func(query string) map[string]int64 {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.ListProperties(w, newRequest("GET", "/api/properties"+query, nil))+ if w.Code != http.StatusOK {+ t.Fatalf("ListProperties%s: expected 200, got %d: %s", query, w.Code, w.Body.String())+ }+ var resp struct {+ Properties []PropertyResponse `json:"properties"`+ }+ json.NewDecoder(w.Body).Decode(&resp)+ out := make(map[string]int64)+ for _, p := range resp.Properties {+ out[p.ID] = p.UsageCount+ }+ return out+ }++ withUsage := counts("?include_archived=true")+ want := map[string]int64{propA.ID: 2, propB.ID: 1, unused.ID: 0}+ for id, n := range want {+ got, ok := withUsage[id]+ if !ok || got != n {+ t.Fatalf("usage_count for %s: got %d (present=%v), want %d", id, got, ok, n)+ }+ }++ catalog := counts("?include_archived=true&include_usage=false")+ for id := range want {+ got, ok := catalog[id]+ if !ok || got != 0 {+ t.Fatalf("include_usage=false for %s: got %d (present=%v), want listed with 0", id, got, ok)+ }+ }+ if _, ok := counts("?include_usage=false")[propB.ID]; ok {+ t.Fatalf("archived property listed without include_archived")+ }++ // Definitions past one scan's column budget are counted by further scans;+ // put real definitions on both sides of the split.+ defs := []db.IssueProperty{{ID: parseUUID(propA.ID)}}+ for len(defs) < propertyUsageKeysPerScan {+ defs = append(defs, db.IssueProperty{ID: parseUUID(uuid.NewString())})+ }+ defs = append(defs, db.IssueProperty{ID: parseUUID(propB.ID)}, db.IssueProperty{ID: parseUUID(unused.ID)})+ usage, err := testHandler.countPropertyUsage(context.Background(), parseUUID(testWorkspaceID), defs)+ if err != nil {+ t.Fatalf("countPropertyUsage across scans: %v", err)+ }+ if len(usage) != len(defs) {+ t.Fatalf("countPropertyUsage across scans: %d counts, want %d", len(usage), len(defs))+ }+ for id, n := range want {+ if usage[id] != n {+ t.Fatalf("usage_count across scans for %s: got %d, want %d", id, usage[id], n)+ }+ }+}++// propertyQueryObserver sits under both h.DB and h.Queries. It counts the+// definition rows the catalog query returns and, for every usage-count query,+// records the largest row count any plan node produced.+type propertyQueryObserver struct {+ dbExecutor+ t *testing.T+ catalogRows int+ usageScans []int64+}++type propertyCatalogRows struct {+ pgx.Rows+ observer *propertyQueryObserver+}++func (r *propertyCatalogRows) Next() bool {+ ok := r.Rows.Next()+ if ok {+ r.observer.catalogRows+++ }+ return ok+}++var usageQueryPattern = regexp.MustCompile(`FROM issue i\b`)++func (o *propertyQueryObserver) observe(ctx context.Context, sql string, args []any) {+ if !usageQueryPattern.MatchString(sql) {+ return+ }+ var plan []struct {+ Plan json.RawMessage `json:"Plan"`+ }+ var raw []byte+ if err := o.dbExecutor.QueryRow(ctx, "EXPLAIN (ANALYZE, FORMAT JSON) "+sql, args...).Scan(&raw); err != nil {+ o.t.Fatalf("explain usage query: %v", err)+ }+ if err := json.Unmarshal(raw, &plan); err != nil || len(plan) != 1 {+ o.t.Fatalf("decode usage plan: %v", err)+ }+ o.usageScans = append(o.usageScans, maxPlanRows(o.t, plan[0].Plan))+}++func maxPlanRows(t *testing.T, raw json.RawMessage) int64 {+ var node struct {+ ActualRows float64 `json:"Actual Rows"`+ ActualLoops float64 `json:"Actual Loops"`+ Plans []json.RawMessage `json:"Plans"`+ }+ if err := json.Unmarshal(raw, &node); err != nil {+ t.Fatalf("decode plan node: %v", err)+ }+ most := int64(node.ActualRows * node.ActualLoops)+ for _, child := range node.Plans {+ most = max(most, maxPlanRows(t, child))+ }+ return most+}++func (o *propertyQueryObserver) Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error) {+ o.observe(ctx, sql, args)+ rows, err := o.dbExecutor.Query(ctx, sql, args...)+ if err != nil || !strings.Contains(sql, "FROM issue_property") {+ return rows, err+ }+ return &propertyCatalogRows{Rows: rows, observer: o}, nil+}++func (o *propertyQueryObserver) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ o.observe(ctx, sql, args)+ return o.dbExecutor.QueryRow(ctx, sql, args...)+}++// Counting usage must read each of the workspace's issues once, never build a+// row per (issue, key): with most issues carrying the counted keys, those rows+// made the count slower than the per-definition scans it replaced. A+// catalog-only request reads only the definitions it returns.+func TestListPropertiesUsageSingleScan(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ suffix := uuid.NewString()[:8]+ ws := dbfx.Workspace(t, "Property usage "+suffix, "prop-usage-"+suffix)+ addProperty := func(name string, archived bool) string {+ t.Helper()+ cols := testutil.Cols{"workspace_id": ws, "name": name, "type": "number"}+ if archived {+ cols["archived_at"] = testutil.Raw("now()")+ }+ return dbfx.Insert(t, "issue_property", cols)+ }+ addIssue := func(propertyIDs ...string) {+ t.Helper()+ props := map[string]int{}+ for i, id := range propertyIDs {+ props[id] = i+ }+ raw, _ := json.Marshal(props)+ dbfx.Issue(t, "property usage "+suffix, testutil.Cols{"workspace_id": ws, "properties": string(raw)})+ }++ // Nine active definitions, all filled on most property-carrying issues —+ // the distribution where a row per (issue, key) costs the most.+ var active []string+ for i := 0; i < 9; i++ {+ active = append(active, addProperty(fmt.Sprintf("Active %d", i), false))+ }+ archived := []string{addProperty("Archived 0", true), addProperty("Archived 1", true)}+ for i := 0; i < 3; i++ {+ addIssue(append(append([]string{}, active...), archived[0])...)+ }+ addIssue(archived[1])+ addIssue()+ const issuesInWorkspace = 5++ list := func(query string) (*propertyQueryObserver, map[string]int64) {+ t.Helper()+ observer := &propertyQueryObserver{dbExecutor: testPool, t: t}+ h := *testHandler+ h.DB = observer+ h.Queries = db.New(observer)+ var resp struct {+ Properties []PropertyResponse `json:"properties"`+ }+ req := testutil.WithHeaders(testutil.JSONRequest(http.MethodGet, "/api/properties"+query, nil),+ "X-User-ID", testUserID, "X-Workspace-ID", ws)+ testutil.Call(t, h.ListProperties, req).Want(http.StatusOK).JSON(&resp)+ counts := make(map[string]int64, len(resp.Properties))+ for _, p := range resp.Properties {+ counts[p.ID] = p.UsageCount+ }+ return observer, counts+ }++ for _, tc := range []struct {+ query string+ want map[string]int64+ }{+ {"", map[string]int64{}},+ {"?include_archived=true", map[string]int64{archived[0]: 3, archived[1]: 1}},+ } {+ for _, id := range active {+ tc.want[id] = 3+ }+ observer, counts := list(tc.query)+ if len(counts) != len(tc.want) {+ t.Fatalf("ListProperties%s: %d definitions, want %d", tc.query, len(counts), len(tc.want))+ }+ for id, n := range tc.want {+ if counts[id] != n {+ t.Fatalf("ListProperties%s: usage_count for %s = %d, want %d", tc.query, id, counts[id], n)+ }+ }+ if len(observer.usageScans) != 1 {+ t.Fatalf("ListProperties%s: %d usage queries, want one scan", tc.query, len(observer.usageScans))+ }+ if rows := observer.usageScans[0]; rows > issuesInWorkspace {+ t.Fatalf("ListProperties%s: a usage plan node produced %d rows for %d issues in the workspace; want no row per (issue, key)",+ tc.query, rows, issuesInWorkspace)+ }+ }++ for _, tc := range []struct {+ query string+ want int+ }{+ {"?include_usage=false", len(active)},+ {"?include_archived=true&include_usage=false", len(active) + len(archived)},+ } {+ observer, counts := list(tc.query)+ if len(observer.usageScans) != 0 || observer.catalogRows != tc.want || len(counts) != tc.want {+ t.Fatalf("ListProperties%s: %d usage queries, %d definition rows read, %d listed; want 0, %d, %d",+ tc.query, len(observer.usageScans), observer.catalogRows, len(counts), tc.want, tc.want)+ }+ }+}++// Counting usage must not read property bags more often than the+// per-definition `properties ? id` queries it replaced, nor read other+// workspaces' bags at all. Under a sequential scan, bags past the TOAST+// threshold are fetched from the TOAST table on every read, so extra reads+// show up as buffer accesses. Large bags both carry and miss the counted+// keys, and another workspace stores large bags too.+func TestPropertyUsageReadsBagsNoMoreThanPerDefinitionScans(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ suffix := uuid.NewString()[:8]+ ws := dbfx.Workspace(t, "Property usage TOAST "+suffix, "prop-toast-"+suffix)+ activeA := dbfx.Insert(t, "issue_property", testutil.Cols{"workspace_id": ws, "name": "Active A", "type": "text"})+ activeB := dbfx.Insert(t, "issue_property", testutil.Cols{"workspace_id": ws, "name": "Active B", "type": "text"})+ archived := dbfx.Insert(t, "issue_property", testutil.Cols{+ "workspace_id": ws, "name": "Archived", "type": "text", "archived_at": testutil.Raw("now()"),+ })+ // Random hex does not compress, so each bag is stored out of line.+ addLargeIssue := func(extraKeys ...string) {+ t.Helper()+ noise := make([]byte, 4096)+ if _, err := rand.Read(noise); err != nil {+ t.Fatal(err)+ }+ props := map[string]string{archived: hex.EncodeToString(noise)}+ for _, key := range extraKeys {+ props[key] = "v"+ }+ raw, _ := json.Marshal(props)+ dbfx.Issue(t, "large property bag", testutil.Cols{"workspace_id": ws, "properties": string(raw)})+ }+ for i := 0; i < 3; i++ {+ addLargeIssue()+ addLargeIssue(activeA, activeB)+ }+ other := dbfx.Workspace(t, "Property usage TOAST other "+suffix, "prop-toast-other-"+suffix)+ for i := 0; i < 3; i++ {+ noise := make([]byte, 4096)+ if _, err := rand.Read(noise); err != nil {+ t.Fatal(err)+ }+ raw, _ := json.Marshal(map[string]string{uuid.NewString(): hex.EncodeToString(noise)})+ dbfx.Issue(t, "other workspace bag", testutil.Cols{"workspace_id": other, "properties": string(raw)})+ }++ tx, err := testPool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(ctx)+ for _, setting := range []string{"enable_indexscan", "enable_bitmapscan", "enable_indexonlyscan"} {+ if _, err := tx.Exec(ctx, "SET LOCAL "+setting+" = off"); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := tx.Exec(ctx, "SET LOCAL max_parallel_workers_per_gather = 0"); err != nil {+ t.Fatal(err)+ }+ explain := func(sql string, args ...any) json.RawMessage {+ t.Helper()+ var raw []byte+ if err := tx.QueryRow(ctx, "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) "+sql, args...).Scan(&raw); err != nil {+ t.Fatalf("explain: %v", err)+ }+ var plan []struct {+ Plan json.RawMessage `json:"Plan"`+ }+ if err := json.Unmarshal(raw, &plan); err != nil || len(plan) != 1 {+ t.Fatalf("decode plan: %v", err)+ }+ return plan[0].Plan+ }+ buffers := func(sql string, args ...any) int64 {+ t.Helper()+ var root struct {+ Hit int64 `json:"Shared Hit Blocks"`+ Read int64 `json:"Shared Read Blocks"`+ }+ if err := json.Unmarshal(explain(sql, args...), &root); err != nil {+ t.Fatalf("decode plan root: %v", err)+ }+ return root.Hit + root.Read+ }+ usageBuffers := func(keys ...string) int64 {+ t.Helper()+ defs := make([]db.IssueProperty, len(keys))+ for i, key := range keys {+ defs[i] = db.IssueProperty{ID: parseUUID(key)}+ }+ query, args := propertyUsageQuery(parseUUID(ws), defs)+ counts := make([]int64, len(keys))+ dest := make([]any, len(keys))+ for i := range counts {+ dest[i] = &counts[i]+ }+ if err := tx.QueryRow(ctx, query, args...).Scan(dest...); err != nil {+ t.Fatalf("usage query for %d definitions: %v", len(keys), err)+ }+ for i, n := range counts {+ if n != 3 {+ t.Fatalf("usage query for %d definitions: count %d = %d, want 3", len(keys), i, n)+ }+ }+ // The scan of issue must filter on workspace_id alone, so no other+ // workspace's bag is ever read; JSON checks belong above it.+ for _, cond := range issueScanConditions(t, explain(query, args...)) {+ if strings.Contains(cond, "properties") {+ t.Fatalf("usage query for %d definitions checks JSON while scanning issue: %s", len(keys), cond)+ }+ }+ return buffers(query, args...)+ }+ perDefinitionBuffers := func(key string) int64 {+ t.Helper()+ return buffers(`SELECT COUNT(*) FROM issue i WHERE i.workspace_id = $1::uuid AND i.properties ? $2::text`, parseUUID(ws), key)+ }++ // Measure the usage queries first: rows other tests add later can only+ // make the per-definition queries read more.+ one := usageBuffers(activeA)+ two := usageBuffers(activeA, activeB)+ scanA, scanB := perDefinitionBuffers(activeA), perDefinitionBuffers(activeB)+ if one > scanA {+ t.Fatalf("one definition: usage count read %d buffers under a sequential scan, more than the %d of one `properties ? id` scan", one, scanA)+ }+ if two > scanA+scanB {+ t.Fatalf("two definitions: usage count read %d buffers under a sequential scan, more than the %d of two `properties ? id` scans", two, scanA+scanB)+ }+}++// issueScanConditions returns the filter and index conditions of every plan+// node that scans the issue table.+func issueScanConditions(t *testing.T, raw json.RawMessage) []string {+ t.Helper()+ var node struct {+ Relation string `json:"Relation Name"`+ Filter string `json:"Filter"`+ IndexCond string `json:"Index Cond"`+ RecheckCond string `json:"Recheck Cond"`+ Plans []json.RawMessage `json:"Plans"`+ }+ if err := json.Unmarshal(raw, &node); err != nil {+ t.Fatalf("decode plan node: %v", err)+ }+ var conds []string+ if node.Relation == "issue" {+ for _, c := range []string{node.Filter, node.IndexCond, node.RecheckCond} {+ if c != "" {+ conds = append(conds, c)+ }+ }+ }+ for _, child := range node.Plans {+ conds = append(conds, issueScanConditions(t, child)...)+ }+ return conds+}+func TestPropertyDefinitionValidation(t *testing.T) {cases := []struct {name stringdiff --git a/server/pkg/db/generated/issue_property.sql.go b/server/pkg/db/generated/issue_property.sql.goindex 88039ae67b..54207130e0 100644--- a/server/pkg/db/generated/issue_property.sql.go+++ b/server/pkg/db/generated/issue_property.sql.go@@ -175,6 +175,7 @@ func (q *Queries) DeleteIssuePropertyValue(ctx context.Context, arg DeleteIssueP}const getIssueProperty = `-- name: GetIssueProperty :one+SELECT id, workspace_id, name, type, description, config, position, archived_at, created_at, updated_at, icon FROM issue_propertyWHERE id = $1 AND workspace_id = $2`@@ -184,6 +185,8 @@ type GetIssuePropertyParams struct {WorkspaceID pgtype.UUID `json:"workspace_id"`}+// usage_count is computed in Go (propertyUsageQuery in+// internal/handler/property.go): it needs one output column per definition.func (q *Queries) GetIssueProperty(ctx context.Context, arg GetIssuePropertyParams) (IssueProperty, error) {row := q.db.QueryRow(ctx, getIssueProperty, arg.ID, arg.WorkspaceID)var i IssueProperty@@ -204,16 +207,10 @@ func (q *Queries) GetIssueProperty(ctx context.Context, arg GetIssuePropertyPara}const listIssueProperties = `-- name: ListIssueProperties :many-SELECT p.id, p.workspace_id, p.name, p.type, p.description, p.config, p.position, p.archived_at, p.created_at, p.updated_at, p.icon,- (- SELECT COUNT(*) FROM issue i- WHERE i.workspace_id = p.workspace_id- AND i.properties ? p.id::text- )::bigint AS usage_count-FROM issue_property p-WHERE p.workspace_id = $1::uuid- AND ($2::bool OR p.archived_at IS NULL)-ORDER BY p.position ASC, LOWER(p.name) ASC+SELECT id, workspace_id, name, type, description, config, position, archived_at, created_at, updated_at, icon FROM issue_property+WHERE workspace_id = $1::uuid+ AND ($2::bool OR archived_at IS NULL)+ORDER BY position ASC, LOWER(name) ASC`type ListIssuePropertiesParams struct {@@ -221,33 +218,17 @@ type ListIssuePropertiesParams struct {IncludeArchived bool `json:"include_archived"`}-type ListIssuePropertiesRow struct {- ID pgtype.UUID `json:"id"`- WorkspaceID pgtype.UUID `json:"workspace_id"`- Name string `json:"name"`- Type string `json:"type"`- Description string `json:"description"`- Config []byte `json:"config"`- Position float64 `json:"position"`- ArchivedAt pgtype.Timestamptz `json:"archived_at"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- UpdatedAt pgtype.Timestamptz `json:"updated_at"`- Icon string `json:"icon"`- UsageCount int64 `json:"usage_count"`-}--// usage_count = number of issues in the workspace that currently carry a-// value for this property. `properties ? id` is a seq scan today; fine at-// the 20-definition / small-workspace scale this feature targets.-func (q *Queries) ListIssueProperties(ctx context.Context, arg ListIssuePropertiesParams) ([]ListIssuePropertiesRow, error) {+// Definition catalog without usage counts — the hot path every issue surface,+// the CLI's name resolution, and every realtime refetch hit.+func (q *Queries) ListIssueProperties(ctx context.Context, arg ListIssuePropertiesParams) ([]IssueProperty, error) {rows, err := q.db.Query(ctx, listIssueProperties, arg.WorkspaceID, arg.IncludeArchived)if err != nil {return nil, err}defer rows.Close()- items := []ListIssuePropertiesRow{}+ items := []IssueProperty{}for rows.Next() {- var i ListIssuePropertiesRow+ var i IssuePropertyif err := rows.Scan(&i.ID,&i.WorkspaceID,@@ -260,7 +241,6 @@ func (q *Queries) ListIssueProperties(ctx context.Context, arg ListIssueProperti&i.CreatedAt,&i.UpdatedAt,&i.Icon,- &i.UsageCount,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/issue_property.sql b/server/pkg/db/queries/issue_property.sqlindex c206ebe495..ee424b9069 100644--- a/server/pkg/db/queries/issue_property.sql+++ b/server/pkg/db/queries/issue_property.sql@@ -1,17 +1,13 @@-- name: ListIssueProperties :many--- usage_count = number of issues in the workspace that currently carry a--- value for this property. `properties ? id` is a seq scan today; fine at--- the 20-definition / small-workspace scale this feature targets.-SELECT p.*,- (- SELECT COUNT(*) FROM issue i- WHERE i.workspace_id = p.workspace_id- AND i.properties ? p.id::text- )::bigint AS usage_count-FROM issue_property p-WHERE p.workspace_id = sqlc.arg('workspace_id')::uuid- AND (sqlc.arg('include_archived')::bool OR p.archived_at IS NULL)-ORDER BY p.position ASC, LOWER(p.name) ASC;+-- Definition catalog without usage counts — the hot path every issue surface,+-- the CLI's name resolution, and every realtime refetch hit.+SELECT * FROM issue_property+WHERE workspace_id = sqlc.arg('workspace_id')::uuid+ AND (sqlc.arg('include_archived')::bool OR archived_at IS NULL)+ORDER BY position ASC, LOWER(name) ASC;++-- usage_count is computed in Go (propertyUsageQuery in+-- internal/handler/property.go): it needs one output column per definition.-- name: GetIssueProperty :oneSELECT * FROM issue_property