# Dashboard Count Query Shape

## Background and goal

Dashboard cluster COUNT currently reuses list query construction, including list ordering and an `organizations` join even when no organization field is referenced. The goal is to remove that work while preserving list results and every existing filter/search behavior.

## Current behavior

- COUNT and LIST share filtering and ordering helpers.
- COUNT may contain `ORDER BY`.
- Cluster-only COUNT may join `organizations` unnecessarily.
- Numeric exact search builds four equality branches, all of which currently join organizations.

## Target contract

- COUNT never contains list ordering.
- COUNT without tenant-dependent predicates reads only `clusters`.
- `tenant_plan`, tenant-name fuzzy search, and tenant-ID branches retain the required organization join.
- LIST retains the organization join needed to return tenant fields and preserves existing ordering and pagination.
- Numeric exact COUNT joins organizations only for branches or filters that need it.
- Response fields and route parameters do not change.

## Affected modules and routes

- Go module: repository root, `github.com/pingcap-inc/clinic`.
- Package: `pkg/datasource`.
- Entrypoint: `cmd/server/main.go`.
- Routes using the shared dashboard datasource include `/dashboard/clusters` and `/dashboard/clusters2`.

Deployment chain: root module -> `cmd/server` -> `clinic` image -> Clinic CD `components=clinic` -> app-delivery `clinic-api` -> Clinic Deployment. No app-delivery configuration change is required. No separate deployment of Internal API, Task Manager, Clinic Data Service, Cloud Server, NGM, or Kong is required for the dashboard route outcome.

## Implementation steps

1. Separate count predicates from list ordering.
2. Decide organization joins from the predicates used by each count path.
3. Preserve fuzzy-search policy and numeric exact-search mode for the following LIST.
4. Add dry-run SQL tests for ordering and join shape, plus related regression tests.

## Exclusions and compatibility

- Do not cache COUNT in this task.
- Do not change `include_total`, `has_more`, search fields, filters, pagination, or result ordering.
- Do not change time predicates or add indexes/migrations.
- Existing request and response contracts remain unchanged.

## Test plan

- `go test ./pkg/datasource -run 'TestDashboard(Count|FuzzyCount|NumericFastCount)' -count=1`
- `go test ./pkg/datasource ./pkg/api/cloud ./pkg/api/internal_api -count=1`
- `go vet ./pkg/datasource ./pkg/api/cloud ./pkg/api/internal_api`

## Staging and release boundary

Validate this stacked change with RDS-03 and Clinic UI at the agreed integration point. Compare generated SQL shape and affected route behavior; use staging `EXPLAIN ANALYZE` only with authorized, redacted parameters. Do not merge until required checks and review pass and the user explicitly authorizes merge. Production release requires separate explicit authorization.
