1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main

import (
	"database/sql"
	"fmt"
	"hash/fnv"
	"io"
	"math/bits"
	"net/url"
	"strings"
)

// sample picks n sites whose URLs differ the most, so that the few hosts
// that make up much of the listing (YouTube, Bluesky, nitter instances,
// feedburner) do not make up the sample too.
//
// Each site URL gets a SimHash fingerprint (urlSimhash), and the sample is
// built by farthest-point sampling on the Hamming distance between them:
// first the site farthest from all others, then, again and again, the site
// whose nearest pick so far is farthest away. Ties go to the site listed
// first. So the same listing gives the same sample.
func sample(db *sql.DB, n int, log io.Writer) error {
	var have int
	if err := db.QueryRow(`SELECT COUNT(*) FROM sample`).Scan(&have); err != nil {
		return err
	}
	if have > 0 {
		return fmt.Errorf("there is a sample of %d already; DELETE FROM sample to draw another", have)
	}

	rows, err := db.Query(`SELECT handle, site_url FROM listing ORDER BY page, rowid`)
	if err != nil {
		return err
	}
	var handles []string
	var hashes []uint64
	seen := map[string]bool{}
	for rows.Next() {
		var h, u string
		if err = rows.Scan(&h, &u); err != nil {
			rows.Close()
			return err
		}
		// Sites listed under several feeds are one page to fetch.
		key := normaliseUrl(u)
		if seen[key] {
			continue
		}
		seen[key] = true
		handles = append(handles, h)
		hashes = append(hashes, urlSimhash(u))
	}
	rows.Close()
	if err = rows.Err(); err != nil {
		return err
	}
	if len(handles) == 0 {
		return fmt.Errorf("the listing is empty; run list first")
	}

	picks, dists := farthestPoints(hashes, n)

	tx, err := db.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	for rank, i := range picks {
		if _, err = tx.Exec(`INSERT INTO sample (handle, rank, simhash, min_dist) VALUES (?,?,?,?)`,
			handles[i], rank, int64(hashes[i]), dists[rank]); err != nil {
			return err
		}
	}
	if err = tx.Commit(); err != nil {
		return err
	}
	fmt.Fprintf(log, "sampled %d of %d sites; the last pick is %d bits from its nearest\n",
		len(picks), len(handles), dists[len(dists)-1])
	return nil
}

// farthestPoints picks up to n of hashes by farthest-point sampling and
// returns their indexes in the order picked, and for each the Hamming
// distance to the nearest one picked before it (64 for the first).
//
// The first pick is the one with the greatest sum of distances to all
// others, which takes all pairs; each further pick takes one pass.
func farthestPoints(hashes []uint64, n int) (picks []int, dists []int) {
	if n > len(hashes) {
		n = len(hashes)
	}
	if n <= 0 {
		return nil, nil
	}
	first, best := 0, -1
	for i, a := range hashes {
		sum := 0
		for _, b := range hashes {
			sum += bits.OnesCount64(a ^ b)
		}
		if sum > best {
			first, best = i, sum
		}
	}

	// nearest[i] is the distance of i to its nearest pick so far; -1 once i
	// is picked.
	nearest := make([]int, len(hashes))
	for i := range nearest {
		nearest[i] = 65
	}
	pick := func(i, d int) {
		picks = append(picks, i)
		dists = append(dists, d)
		nearest[i] = -1
		for j, b := range hashes {
			if nearest[j] < 0 {
				continue
			}
			if d := bits.OnesCount64(hashes[i] ^ b); d < nearest[j] {
				nearest[j] = d
			}
		}
	}
	pick(first, 64)
	for len(picks) < n {
		next, far := -1, -1
		for j, d := range nearest {
			if d > far {
				next, far = j, d
			}
		}
		pick(next, far)
	}
	return picks, dists
}

// normaliseUrl is the part of a URL that tells sites apart: without scheme,
// "www." and trailing slash, in lower case.
func normaliseUrl(s string) string {
	s = strings.ToLower(strings.TrimSpace(s))
	if u, err := url.Parse(s); err == nil && u.Host != "" {
		s = u.Host + u.EscapedPath()
		if u.RawQuery != "" {
			s += "?" + u.RawQuery
		}
	}
	s = strings.TrimPrefix(s, "www.")
	return strings.TrimRight(s, "/")
}

// urlSimhash is a 64-bit SimHash of a site URL, over these features of its
// normalised form: each label of the host, each segment of the path (with the
// query), and each character trigram of the whole. Two URLs that share most
// features get fingerprints a few bits apart: two YouTube channels, or two
// blogs on the same host. Each feature counts once.
func urlSimhash(s string) uint64 {
	n := normaliseUrl(s)
	host, path, _ := strings.Cut(n, "/")
	var features []string
	for _, l := range strings.Split(host, ".") {
		if l != "" {
			features = append(features, "h:"+l)
		}
	}
	for _, seg := range strings.FieldsFunc(path, func(r rune) bool { return r == '/' || r == '?' || r == '&' }) {
		features = append(features, "p:"+seg)
	}
	r := []rune(n)
	for i := 0; i+3 <= len(r); i++ {
		features = append(features, "t:"+string(r[i:i+3]))
	}
	if len(features) == 0 {
		features = append(features, "t:"+n)
	}

	var v [64]int
	seen := map[string]bool{}
	for _, f := range features {
		if seen[f] {
			continue
		}
		seen[f] = true
		h := fnv.New64a()
		h.Write([]byte(f))
		x := h.Sum64()
		for b := 0; b < 64; b++ {
			if x&(1<<b) != 0 {
				v[b]++
			} else {
				v[b]--
			}
		}
	}
	var res uint64
	for b := 0; b < 64; b++ {
		if v[b] > 0 {
			res |= 1 << b
		}
	}
	return res
}