pgshrink 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pgshrink/__init__.py +3 -0
- pgshrink/cli.py +120 -0
- pgshrink/db.py +131 -0
- pgshrink/measure.py +144 -0
- pgshrink/sql.py +47 -0
- pgshrink-0.1.0.dist-info/METADATA +206 -0
- pgshrink-0.1.0.dist-info/RECORD +10 -0
- pgshrink-0.1.0.dist-info/WHEEL +4 -0
- pgshrink-0.1.0.dist-info/entry_points.txt +2 -0
- pgshrink-0.1.0.dist-info/licenses/LICENSE +202 -0
pgshrink/__init__.py
ADDED
pgshrink/cli.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""pgshrink analyze: sample a pgvector column, measure each compressed layout, print savings and SQL."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from . import __version__, db, measure, sql
|
|
8
|
+
|
|
9
|
+
PAGE, PAGE_FREE = 8192, 8168
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def hnsw_index_bytes(rows: int, value_bytes: int, m: int = 16) -> int:
|
|
13
|
+
"""Estimated pgvector HNSW index size. Rows pack whole into 8 KB pages; each costs its value plus ~98 + 12*m bytes
|
|
14
|
+
of tuple headers and layer-0 links. Fitted on real indexes (171k x 1024 dims, m=16, within 3%): a 4 KB vector
|
|
15
|
+
fills a page alone, so halfvec shrinks the index ~3x, not 2x."""
|
|
16
|
+
per_page = max(1, PAGE_FREE // (value_bytes + 98 + 12 * m))
|
|
17
|
+
return -(-rows // per_page) * PAGE
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def human(b):
|
|
21
|
+
for unit in ("B", "KB", "MB", "GB", "TB"):
|
|
22
|
+
if b < 1024 or unit == "TB":
|
|
23
|
+
return f"{b:.1f} {unit}" if unit != "B" else f"{int(b)} B"
|
|
24
|
+
b /= 1024
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def analyze(a):
|
|
28
|
+
t0 = time.time()
|
|
29
|
+
with db.connect(a.dsn) as conn:
|
|
30
|
+
col = db.inspect(conn, a.table, a.column)
|
|
31
|
+
metric = a.metric or col.metric
|
|
32
|
+
if metric is None:
|
|
33
|
+
raise SystemExit("no single vector index tells the distance: pass --metric cosine|ip|l2")
|
|
34
|
+
q_keys, Q = db.queries(conn, col, a.queries, a.seed)
|
|
35
|
+
rows, scanned = measure.evaluate(db.stream(conn, col, a.max_rows, a.seed), Q, q_keys, metric, a.k, a.seed)
|
|
36
|
+
|
|
37
|
+
current = 8 + 4 * col.dims
|
|
38
|
+
hnsw = [i for i in col.indexes if i["method"] == "hnsw"]
|
|
39
|
+
m = hnsw[0]["m"] if hnsw else 16
|
|
40
|
+
out = []
|
|
41
|
+
for r in rows:
|
|
42
|
+
lay = r["layout"]
|
|
43
|
+
out.append({
|
|
44
|
+
"layout": lay.name, "kind": lay.kind, "dims": lay.dims, "rerank": lay.rerank,
|
|
45
|
+
"bytes_per_value": lay.payload_bytes(),
|
|
46
|
+
"index_bytes_est": hnsw_index_bytes(col.rows, lay.payload_bytes(), m),
|
|
47
|
+
"fidelity": round(r["fidelity"], 4), "ci95": [round(x, 4) for x in r["ci"]],
|
|
48
|
+
"needs_full_column": lay.rerank > 1,
|
|
49
|
+
})
|
|
50
|
+
ok = [o for o in out if o["ci95"][0] >= a.target]
|
|
51
|
+
best = min(ok, key=lambda o: (o["index_bytes_est"], o["rerank"])) if ok else None
|
|
52
|
+
report = {
|
|
53
|
+
"pgshrink": __version__,
|
|
54
|
+
"column": f"{col.schema}.{col.table}.{col.column}", "dims": col.dims, "rows": col.rows, "metric": metric,
|
|
55
|
+
"scanned": scanned, "full_scan": scanned >= col.rows * 0.99, "queries": len(Q), "k": a.k, "seed": a.seed, "target": a.target,
|
|
56
|
+
"current": {"bytes_per_value": current, "index_bytes": hnsw[0]["bytes"] if hnsw else None,
|
|
57
|
+
"table_bytes": col.table_bytes, "indexes": col.indexes},
|
|
58
|
+
"layouts": out, "recommended": best["layout"] if best else None,
|
|
59
|
+
"seconds": round(time.time() - t0, 1),
|
|
60
|
+
}
|
|
61
|
+
if best:
|
|
62
|
+
lay = next(r["layout"] for r in rows if r["layout"].name == best["layout"])
|
|
63
|
+
report["sql"] = sql.migration(col.schema, col.table, col.column, lay, col.dims, metric, a.k)
|
|
64
|
+
return report
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def print_report(r, out=sys.stdout):
|
|
68
|
+
w = out.write
|
|
69
|
+
cur = r["current"]
|
|
70
|
+
w(f"\n{r['column']} vector({r['dims']}), {r['rows']:,} rows, {r['metric']} distance\n")
|
|
71
|
+
w(f"{r['queries']} sampled queries vs exact search over {r['scanned']:,} rows, top-{r['k']} ({r['seconds']} s)\n")
|
|
72
|
+
if not r["full_scan"]:
|
|
73
|
+
w(f"note: only {r['scanned']:,} of {r['rows']:,} rows were scanned (--max-rows); rerank results are optimistic\n")
|
|
74
|
+
w("\n")
|
|
75
|
+
head = f"{'layout':<30}{'bytes/vec':>10} {'index size (est.)':>18} {'same top-' + str(r['k']) + ' as today':>22}\n"
|
|
76
|
+
w(head)
|
|
77
|
+
idx = human(cur["index_bytes"]) if cur["index_bytes"] else "no HNSW index"
|
|
78
|
+
w(f"{'vector (current)':<30}{cur['bytes_per_value']:>10} {idx:>18} {'100%':>22}\n")
|
|
79
|
+
for o in r["layouts"]:
|
|
80
|
+
lo, hi = o["ci95"]
|
|
81
|
+
mark = " <- recommended" if o["layout"] == r["recommended"] else ""
|
|
82
|
+
fid = f"{o['fidelity']:.1%} [{lo:.1%}, {hi:.1%}]"
|
|
83
|
+
w(f"{o['layout']:<30}{o['bytes_per_value']:>10} {human(o['index_bytes_est']):>18} {fid:>22}{mark}\n")
|
|
84
|
+
w("\n")
|
|
85
|
+
if not r["recommended"]:
|
|
86
|
+
w(f"No layout keeps the lower 95% bound above {r['target']:.0%}: keep the current index.\n")
|
|
87
|
+
return
|
|
88
|
+
w(f"Recommended: {r['recommended']} (smallest index whose 95% lower bound is >= {r['target']:.0%}).\n")
|
|
89
|
+
if any(o["layout"] == r["recommended"] and o["needs_full_column"] for o in r["layouts"]):
|
|
90
|
+
w("Rerank reads the original column: the index shrinks, the table does not.\n")
|
|
91
|
+
w("\n" + r["sql"] + "\n")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def main(argv=None):
|
|
95
|
+
p = argparse.ArgumentParser(prog="pgshrink", description=__doc__)
|
|
96
|
+
p.add_argument("--version", action="version", version=f"pgshrink {__version__}")
|
|
97
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
98
|
+
an = sub.add_parser("analyze", help="measure compressed layouts for one vector column (read-only)")
|
|
99
|
+
an.add_argument("dsn", help="PostgreSQL connection string, e.g. postgresql://user@host/db")
|
|
100
|
+
an.add_argument("--table", required=True, help="table, optionally schema-qualified")
|
|
101
|
+
an.add_argument("--column", required=True)
|
|
102
|
+
an.add_argument("--metric", choices=measure.METRICS, help="distance; default: read from the existing index")
|
|
103
|
+
an.add_argument("--queries", type=int, default=200, help="random rows used as queries (default 200)")
|
|
104
|
+
an.add_argument("--max-rows", type=int, default=2_000_000,
|
|
105
|
+
help="scan at most this many rows; bigger tables use a random subset (default 2,000,000)")
|
|
106
|
+
an.add_argument("--k", type=int, default=10, help="top-k to compare (default 10)")
|
|
107
|
+
an.add_argument("--target", type=float, default=0.95, help="minimum lower 95%% bound of fidelity (default 0.95)")
|
|
108
|
+
an.add_argument("--seed", type=int, default=0)
|
|
109
|
+
an.add_argument("--json", action="store_true", help="print the full report as JSON")
|
|
110
|
+
a = p.parse_args(argv)
|
|
111
|
+
report = analyze(a)
|
|
112
|
+
if a.json:
|
|
113
|
+
report.pop("seconds")
|
|
114
|
+
print(json.dumps(report, indent=2))
|
|
115
|
+
else:
|
|
116
|
+
print_report(report)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
if __name__ == "__main__":
|
|
120
|
+
main()
|
pgshrink/db.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Read-only access to the pgvector column: introspection and a reproducible random sample."""
|
|
2
|
+
import re
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import psycopg
|
|
7
|
+
from pgvector.psycopg import register_vector
|
|
8
|
+
from psycopg import sql
|
|
9
|
+
|
|
10
|
+
OPCLASS_METRIC = {"vector_cosine_ops": "cosine", "vector_ip_ops": "ip", "vector_l2_ops": "l2"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass
|
|
14
|
+
class Column:
|
|
15
|
+
schema: str
|
|
16
|
+
table: str
|
|
17
|
+
column: str
|
|
18
|
+
dims: int
|
|
19
|
+
rows: int
|
|
20
|
+
indexes: list # [{"name", "method", "opclass", "bytes", "m"}]
|
|
21
|
+
table_bytes: int
|
|
22
|
+
|
|
23
|
+
@property
|
|
24
|
+
def metric(self):
|
|
25
|
+
found = {OPCLASS_METRIC[i["opclass"]] for i in self.indexes if i["opclass"] in OPCLASS_METRIC}
|
|
26
|
+
return found.pop() if len(found) == 1 else None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def connect(dsn: str, timeout_s: int = 300) -> psycopg.Connection:
|
|
30
|
+
"""Every transaction read-only: pgshrink never writes."""
|
|
31
|
+
conn = psycopg.connect(dsn, options=f"-c default_transaction_read_only=on -c statement_timeout={timeout_s * 1000}")
|
|
32
|
+
register_vector(conn)
|
|
33
|
+
return conn
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _split(table: str):
|
|
37
|
+
schema, _, name = table.rpartition(".")
|
|
38
|
+
return schema or "public", name
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def inspect(conn, table: str, column: str) -> Column:
|
|
42
|
+
schema, name = _split(table)
|
|
43
|
+
rel = f"{schema}.{name}"
|
|
44
|
+
with conn.cursor() as cur:
|
|
45
|
+
cur.execute(
|
|
46
|
+
"SELECT format_type(a.atttypid, a.atttypmod) FROM pg_attribute a "
|
|
47
|
+
"WHERE a.attrelid = to_regclass(%s) AND a.attname = %s AND NOT a.attisdropped",
|
|
48
|
+
(sql.Identifier(schema, name).as_string(conn), column),
|
|
49
|
+
)
|
|
50
|
+
row = cur.fetchone()
|
|
51
|
+
if row is None:
|
|
52
|
+
raise SystemExit(f"column {column!r} not found in {rel}")
|
|
53
|
+
m = re.fullmatch(r"vector\((\d+)\)", row[0])
|
|
54
|
+
if not m:
|
|
55
|
+
raise SystemExit(f"{rel}.{column} is {row[0]}; pgshrink v0.1 supports vector(n) columns only")
|
|
56
|
+
ident = sql.Identifier(schema, name).as_string(conn)
|
|
57
|
+
cur.execute("SELECT GREATEST(reltuples, 0)::bigint, pg_table_size(to_regclass(%s)) FROM pg_class WHERE oid = to_regclass(%s)",
|
|
58
|
+
(ident, ident))
|
|
59
|
+
rows, table_bytes = cur.fetchone()
|
|
60
|
+
if rows == 0: # never analyzed: count once
|
|
61
|
+
cur.execute(sql.SQL("SELECT count(*) FROM {}").format(sql.Identifier(schema, name)))
|
|
62
|
+
rows = cur.fetchone()[0]
|
|
63
|
+
cur.execute(
|
|
64
|
+
"SELECT i.relname, am.amname, opc.opcname, pg_relation_size(i.oid), "
|
|
65
|
+
"COALESCE((SELECT split_part(o, '=', 2)::int FROM unnest(i.reloptions) o WHERE o LIKE 'm=%%'), 16) "
|
|
66
|
+
"FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid JOIN pg_am am ON am.oid = i.relam "
|
|
67
|
+
"JOIN pg_opclass opc ON opc.oid = x.indclass[0] "
|
|
68
|
+
"JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = x.indkey[0] "
|
|
69
|
+
"WHERE x.indrelid = to_regclass(%s) AND a.attname = %s",
|
|
70
|
+
(ident, column),
|
|
71
|
+
)
|
|
72
|
+
indexes = [dict(zip(("name", "method", "opclass", "bytes", "m"), r)) for r in cur.fetchall()]
|
|
73
|
+
return Column(schema, name, column, int(m.group(1)), int(rows), indexes, int(table_bytes))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _key(ctid: str) -> int:
|
|
77
|
+
blk, off = ctid.strip("()").split(",")
|
|
78
|
+
return int(blk) * 65536 + int(off)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _from(col: Column, pct: float | None, seed: int):
|
|
82
|
+
t = sql.Identifier(col.schema, col.table)
|
|
83
|
+
if pct is None or pct >= 100:
|
|
84
|
+
return sql.SQL("{}").format(t)
|
|
85
|
+
return sql.SQL("{} TABLESAMPLE BERNOULLI ({}) REPEATABLE ({})").format(t, sql.Literal(pct), sql.Literal(seed))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def queries(conn, col: Column, n: int, seed: int = 0):
|
|
89
|
+
"""About n random rows used as queries: (row keys from ctid, vectors). Same rows on every run with the same seed."""
|
|
90
|
+
pct = min(100.0, 100.0 * n * 1.5 / max(col.rows, 1))
|
|
91
|
+
q = sql.SQL("SELECT ctid::text, {c} FROM {f} WHERE {c} IS NOT NULL LIMIT {n}").format(
|
|
92
|
+
c=sql.Identifier(col.column), f=_from(col, pct, seed + 1), n=sql.Literal(n))
|
|
93
|
+
with conn.cursor() as cur:
|
|
94
|
+
rows = cur.execute(q).fetchall()
|
|
95
|
+
if not rows:
|
|
96
|
+
raise SystemExit("no non-null vectors found")
|
|
97
|
+
return np.array([_key(r[0]) for r in rows], np.int64), np.array([r[1].to_numpy() for r in rows], np.float32)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def stream(conn, col: Column, max_rows: int, seed: int = 0, chunk_rows: int = 50_000):
|
|
101
|
+
"""Yield (row keys, vectors) for every non-null row (or a random max_rows subset), via COPY ... (FORMAT BINARY).
|
|
102
|
+
|
|
103
|
+
Fixed-size records (ctid + vector(d)) are decoded with one numpy view per chunk, no per-row Python work."""
|
|
104
|
+
d = col.dims
|
|
105
|
+
rec = np.dtype([("nf", ">i2"), ("l1", ">i4"), ("blk", ">u4"), ("off", ">u2"),
|
|
106
|
+
("l2", ">i4"), ("dim", ">i2"), ("unused", ">i2"), ("v", ">f4", (d,))])
|
|
107
|
+
pct = None if col.rows <= max_rows else 100.0 * max_rows / col.rows
|
|
108
|
+
q = sql.SQL("COPY (SELECT ctid, {c} FROM {f} WHERE {c} IS NOT NULL) TO STDOUT (FORMAT BINARY)").format(
|
|
109
|
+
c=sql.Identifier(col.column), f=_from(col, pct, seed))
|
|
110
|
+
buf, header = bytearray(), True
|
|
111
|
+
want = rec.itemsize * chunk_rows
|
|
112
|
+
with conn.cursor() as cur, cur.copy(q) as cp:
|
|
113
|
+
for data in cp:
|
|
114
|
+
buf += data
|
|
115
|
+
if header and len(buf) >= 19:
|
|
116
|
+
ext = int.from_bytes(buf[15:19], "big")
|
|
117
|
+
del buf[: 19 + ext]
|
|
118
|
+
header = False
|
|
119
|
+
while not header and len(buf) >= want:
|
|
120
|
+
yield _decode(buf[:want], rec, d)
|
|
121
|
+
del buf[:want]
|
|
122
|
+
n = len(buf) // rec.itemsize # the 2-byte trailer is left over
|
|
123
|
+
if n:
|
|
124
|
+
yield _decode(buf[: n * rec.itemsize], rec, d)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _decode(b, rec, d):
|
|
128
|
+
a = np.frombuffer(bytes(b), dtype=rec)
|
|
129
|
+
if (a["dim"] != d).any() or (a["l2"] != 4 + 4 * d).any():
|
|
130
|
+
raise SystemExit("unexpected vector format in COPY output")
|
|
131
|
+
return a["blk"].astype(np.int64) * 65536 + a["off"], a["v"].astype(np.float32)
|
pgshrink/measure.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Pure numpy: exact neighbors, compressed layouts, top-k fidelity with bootstrap CI.
|
|
2
|
+
|
|
3
|
+
Fidelity = share of the exact top-k (on the current vectors) that a layout also returns in its top-k.
|
|
4
|
+
It measures "same results as today", not task quality: no labels are needed or used.
|
|
5
|
+
|
|
6
|
+
The corpus is streamed in chunks, so queries are compared against the whole table, not a sample of it:
|
|
7
|
+
on a sample, "rerank 100 candidates" would cover a much larger share of the rows and look better than it is.
|
|
8
|
+
"""
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
METRICS = ("cosine", "ip", "l2")
|
|
14
|
+
RERANKS = (1, 4, 10)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Layout:
|
|
19
|
+
name: str
|
|
20
|
+
kind: str # "halfvec" | "binary"
|
|
21
|
+
dims: int # dims kept (prefix truncation via subvector when < full)
|
|
22
|
+
rerank: int = 1 # oversampling factor; 1 = no rerank. Rerank reads the original column.
|
|
23
|
+
|
|
24
|
+
def payload_bytes(self) -> int:
|
|
25
|
+
"""Bytes of one indexed value (pgvector on-disk format: 8-byte header + data)."""
|
|
26
|
+
return 8 + (2 * self.dims if self.kind == "halfvec" else (self.dims + 7) // 8)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def truncations(dim: int) -> list[int]:
|
|
30
|
+
return [m for m in (dim // 2, dim // 4) if m >= 64]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def layouts(dim: int) -> list[Layout]:
|
|
34
|
+
out = [Layout("halfvec", "halfvec", dim)] + [Layout(f"halfvec, {m} dims", "halfvec", m) for m in truncations(dim)]
|
|
35
|
+
out += [Layout("binary" + (f" + rerank x{o}" if o > 1 else ", no rerank"), "binary", dim, o) for o in RERANKS]
|
|
36
|
+
out += [Layout(f"binary {m} dims + rerank x10", "binary", m, 10) for m in truncations(dim)]
|
|
37
|
+
return out
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _unit(x):
|
|
41
|
+
return x / np.maximum(np.linalg.norm(x, axis=1, keepdims=True), 1e-12)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def scores(D, Q, metric):
|
|
45
|
+
"""Higher = closer, with the same ranking as pgvector's <=> (cosine), <#> (ip), <-> (l2)."""
|
|
46
|
+
if metric == "cosine":
|
|
47
|
+
return _unit(Q) @ _unit(D).T
|
|
48
|
+
if metric == "ip":
|
|
49
|
+
return Q @ D.T
|
|
50
|
+
if metric == "l2":
|
|
51
|
+
return 2 * (Q @ D.T) - (D * D).sum(1)[None, :]
|
|
52
|
+
raise ValueError(f"metric must be one of {METRICS}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def topk(S, k):
|
|
56
|
+
k = min(k, S.shape[1])
|
|
57
|
+
idx = np.argpartition(-S, kth=k - 1, axis=1)[:, :k]
|
|
58
|
+
order = np.take_along_axis(S, idx, axis=1).argsort(axis=1, kind="stable")[:, ::-1]
|
|
59
|
+
return np.take_along_axis(idx, order, axis=1)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _f16(x):
|
|
63
|
+
return x.astype(np.float16).astype(np.float32)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _bits(x):
|
|
67
|
+
return np.where(x > 0, 1.0, -1.0).astype(np.float32) # binary_quantize: 1 where > 0; ±1 dot ranks like -hamming
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Running:
|
|
71
|
+
"""Per-query running top-c of (score, row id[, exact score]) across chunks."""
|
|
72
|
+
|
|
73
|
+
def __init__(self, nq, c):
|
|
74
|
+
self.c, self.s, self.i, self.x = c, np.full((nq, 0), -np.inf), np.zeros((nq, 0), np.int64), None
|
|
75
|
+
|
|
76
|
+
def add(self, S, ids, exact=None):
|
|
77
|
+
s = np.concatenate([self.s, S], 1)
|
|
78
|
+
i = np.concatenate([self.i, np.broadcast_to(ids, S.shape)], 1)
|
|
79
|
+
sel = topk(s, self.c)
|
|
80
|
+
self.s, self.i = np.take_along_axis(s, sel, 1), np.take_along_axis(i, sel, 1)
|
|
81
|
+
if exact is not None:
|
|
82
|
+
x = exact if self.x is None else np.concatenate([self.x, exact], 1)
|
|
83
|
+
self.x = np.take_along_axis(x, sel, 1)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def neighbors(chunks, Q, q_keys=None, metric="cosine", k=10):
|
|
87
|
+
"""chunks: iterable of (row_keys int64[n], D float32[n, d]); rows whose key equals a query's key are skipped
|
|
88
|
+
for that query (a query must not find itself). Row ids are positions in the stream.
|
|
89
|
+
Returns (exact top-k ids, {layout: top-k ids}, rows scanned)."""
|
|
90
|
+
Q = np.asarray(Q, np.float32)
|
|
91
|
+
dim = Q.shape[1]
|
|
92
|
+
q_keys = np.full(len(Q), -1, np.int64) if q_keys is None else np.asarray(q_keys, np.int64)
|
|
93
|
+
exact = Running(len(Q), k)
|
|
94
|
+
half = {m: Running(len(Q), k) for m in [dim, *truncations(dim)]}
|
|
95
|
+
cmax = k * max(RERANKS)
|
|
96
|
+
binary = {m: Running(len(Q), cmax) for m in [dim, *truncations(dim)]}
|
|
97
|
+
Qh = {m: _f16(Q[:, :m]) for m in half}
|
|
98
|
+
Qb = {m: _bits(Q[:, :m]) for m in binary}
|
|
99
|
+
seen = 0
|
|
100
|
+
for keys, D in chunks:
|
|
101
|
+
D = np.asarray(D, np.float32)
|
|
102
|
+
ids = np.arange(seen, seen + len(D), dtype=np.int64)[None, :]
|
|
103
|
+
self_hit = q_keys[:, None] == np.asarray(keys, np.int64)[None, :]
|
|
104
|
+
Se = np.where(self_hit, -np.inf, scores(D, Q, metric)).astype(np.float32)
|
|
105
|
+
exact.add(Se, ids)
|
|
106
|
+
for m, r in half.items():
|
|
107
|
+
r.add(np.where(self_hit, -np.inf, scores(_f16(D[:, :m]), Qh[m], metric)).astype(np.float32), ids)
|
|
108
|
+
for m, r in binary.items():
|
|
109
|
+
# Hamming scores are integers and tie a lot: break ties by row (lower first) so results don't depend on chunking
|
|
110
|
+
hb = (Qb[m] @ _bits(D[:, :m]).T).astype(np.float64) - ids * 1e-9
|
|
111
|
+
r.add(np.where(self_hit, -np.inf, hb), ids, Se)
|
|
112
|
+
seen += len(D)
|
|
113
|
+
got = {}
|
|
114
|
+
for lay in layouts(dim):
|
|
115
|
+
if lay.kind == "halfvec":
|
|
116
|
+
got[lay] = half[lay.dims].i
|
|
117
|
+
else:
|
|
118
|
+
r, n = binary[lay.dims], k * lay.rerank
|
|
119
|
+
cand_i, cand_x = r.i[:, :n], r.x[:, :n]
|
|
120
|
+
got[lay] = cand_i[:, :k] if lay.rerank == 1 else np.take_along_axis(cand_i, topk(cand_x, k), 1)
|
|
121
|
+
return exact.i, got, seen
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def evaluate(chunks, Q, q_keys=None, metric="cosine", k=10, seed=0):
|
|
125
|
+
"""One row per layout (fidelity mean and 95% CI) and the number of rows scanned."""
|
|
126
|
+
truth, got, seen = neighbors(chunks, Q, q_keys, metric, k)
|
|
127
|
+
rows = []
|
|
128
|
+
for lay, ids in got.items():
|
|
129
|
+
f = fidelity(truth, ids)
|
|
130
|
+
lo, hi = bootstrap_ci(f, seed=seed)
|
|
131
|
+
rows.append({"layout": lay, "fidelity": float(f.mean()), "ci": (lo, hi)})
|
|
132
|
+
return rows, seen
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def fidelity(exact, approx):
|
|
136
|
+
"""Per-query share of the exact top-k found in the approximate top-k."""
|
|
137
|
+
k = exact.shape[1]
|
|
138
|
+
return np.array([len(set(e) & set(a)) / k for e, a in zip(exact, approx)])
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def bootstrap_ci(x, n=2000, alpha=0.05, seed=0):
|
|
142
|
+
rng = np.random.default_rng(seed)
|
|
143
|
+
means = x[rng.integers(0, len(x), size=(n, len(x)))].mean(1)
|
|
144
|
+
return float(np.quantile(means, alpha / 2)), float(np.quantile(means, 1 - alpha / 2))
|
pgshrink/sql.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""SQL to adopt a layout. pgshrink only prints it; it never runs it."""
|
|
2
|
+
from .measure import Layout
|
|
3
|
+
|
|
4
|
+
OPS = {"cosine": ("<=>", "cosine"), "ip": ("<#>", "ip"), "l2": ("<->", "l2")}
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _q(ident):
|
|
8
|
+
"""Quoted (optionally schema-qualified) identifier."""
|
|
9
|
+
return ".".join('"' + p.replace('"', '""') + '"' for p in ident)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _expr(col: str, lay: Layout, full_dims: int, value: str) -> str:
|
|
13
|
+
v = value if lay.dims == full_dims else f"subvector({value}, 1, {lay.dims})"
|
|
14
|
+
if lay.kind == "halfvec":
|
|
15
|
+
return f"({v})::halfvec({lay.dims})"
|
|
16
|
+
return f"binary_quantize({v})::bit({lay.dims})"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def migration(schema: str, table: str, column: str, lay: Layout, full_dims: int, metric: str, k: int = 10) -> str:
|
|
20
|
+
op, suffix = OPS[metric]
|
|
21
|
+
t, c = _q((schema, table)), _q((column,))
|
|
22
|
+
idx = _q((f"{table}_{column}_{lay.kind}{lay.dims}_idx",))
|
|
23
|
+
col_expr = _expr(c, lay, full_dims, c)
|
|
24
|
+
q_expr = _expr(c, lay, full_dims, f"$1::vector({full_dims})")
|
|
25
|
+
if lay.kind == "halfvec":
|
|
26
|
+
ops, dist = f"halfvec_{suffix}_ops", op
|
|
27
|
+
else:
|
|
28
|
+
ops, dist = "bit_hamming_ops", "<~>"
|
|
29
|
+
lines = [
|
|
30
|
+
"-- 1. Build the new index without blocking writes (test on a copy first).",
|
|
31
|
+
f"CREATE INDEX CONCURRENTLY IF NOT EXISTS {idx} ON {t} USING hnsw (({col_expr}) {ops});",
|
|
32
|
+
"",
|
|
33
|
+
"-- 2. Query through the same expression, so the planner uses the new index.",
|
|
34
|
+
]
|
|
35
|
+
if lay.rerank == 1:
|
|
36
|
+
lines += [f"SELECT * FROM {t} ORDER BY {col_expr} {dist} {q_expr} LIMIT {k};"]
|
|
37
|
+
else:
|
|
38
|
+
n = k * lay.rerank
|
|
39
|
+
lines += [
|
|
40
|
+
f"-- Rerank: {n} candidates from the compressed index, exact order from the original column.",
|
|
41
|
+
*([f"SET hnsw.ef_search = {max(n, 40)};"] if n > 40 else []),
|
|
42
|
+
"SELECT * FROM (",
|
|
43
|
+
f" SELECT * FROM {t} ORDER BY {col_expr} {dist} {q_expr} LIMIT {n}",
|
|
44
|
+
f") candidates ORDER BY {c} {op} $1::vector({full_dims}) LIMIT {k};",
|
|
45
|
+
]
|
|
46
|
+
lines += ["", "-- 3. When the new queries are live, drop the old index on the column to free its space."]
|
|
47
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pgshrink
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Measure how much smaller your pgvector embeddings can get on your own data, and get the SQL to do it.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.10
|
|
8
|
+
Requires-Dist: numpy>=1.26
|
|
9
|
+
Requires-Dist: pgvector>=0.4
|
|
10
|
+
Requires-Dist: psycopg[binary]>=3.2
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# pgshrink
|
|
14
|
+
|
|
15
|
+
**How much smaller can your pgvector index get without changing your search results? Measure it on your own data in seconds, then get the SQL.**
|
|
16
|
+
|
|
17
|
+
[](https://github.com/alessandroamormino/pgshrink/actions/workflows/ci.yml)
|
|
18
|
+
[](LICENSE)
|
|
19
|
+

|
|
20
|
+

|
|
21
|
+
|
|
22
|
+

|
|
23
|
+
|
|
24
|
+
pgvector can store and index vectors as `halfvec` (16-bit), as `bit` via `binary_quantize()`, or truncated with `subvector()`. The docs say to quantize at scale, but they can't tell you how much quality *your* embeddings lose. That depends on your model and your data.
|
|
25
|
+
|
|
26
|
+
`pgshrink` reads your vector column and tries every layout pgvector supports. For each one it tells you:
|
|
27
|
+
|
|
28
|
+
- **fidelity**: how often you get the same top-k results as today, with a 95% confidence interval;
|
|
29
|
+
- **index size**: how large the HNSW index would be, from a model fitted on real pgvector indexes;
|
|
30
|
+
- **the SQL**: the index and the query to switch to the smallest layout that keeps your results.
|
|
31
|
+
|
|
32
|
+
It needs no labels and no test queries, and it **never writes to your database**.
|
|
33
|
+
|
|
34
|
+
## Example: 171k documents, 1024-dim embeddings
|
|
35
|
+
|
|
36
|
+
The demo above runs on TREC-COVID embedded with Qwen3-Embedding-0.6B. We then built every recommended index and queried it through real pgvector HNSW to check the predictions ([full method](docs/validation.md)):
|
|
37
|
+
|
|
38
|
+
| layout | HNSW index | pgshrink fidelity (predicted) | real HNSW fidelity | p50 query |
|
|
39
|
+
|---|---|---|---|---|
|
|
40
|
+
| `vector` (today) | 1338 MB | 100% | 100% | 324 ms\* |
|
|
41
|
+
| `halfvec` | **446 MB** | 100.0% | 98.1% | 2.2 ms |
|
|
42
|
+
| `binary_quantize` + rerank ×10 | **70 MB** | 98.9% | 97.6% | 2.0 ms |
|
|
43
|
+
|
|
44
|
+
\* The 1.3 GB index did not fit in this server's memory and the compressed ones did. The speedup depends on your hardware and settings, so measure it on yours. The index sizes and fidelity numbers are what pgshrink predicts.
|
|
45
|
+
|
|
46
|
+
Two things people usually don't expect:
|
|
47
|
+
- **`halfvec` makes the index ~3× smaller, not 2×.** pgvector packs whole rows into 8 KB pages, so a 4 KB `vector` fills a page alone, while three `halfvec` rows fit in one.
|
|
48
|
+
- **Binary + rerank shrinks the index ~19× and keeps ~98% of results.** The rerank reads the original column, so the *table* stays the same size. Only the index, which is what needs to stay in RAM, shrinks.
|
|
49
|
+
|
|
50
|
+
## Install
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install pgshrink # or: uv tool install pgshrink
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
You need Python 3.10+ and network access to your Postgres. Nothing is installed in the database.
|
|
57
|
+
|
|
58
|
+
## Quick start
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pgshrink analyze "postgresql://user@host:5432/db" --table documents --column embedding
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Pass the password via `PGPASSWORD` or `~/.pgpass` rather than in the URL. pgshrink reads the distance (cosine, inner product or L2) from your existing vector index; if there is none, add `--metric cosine`.
|
|
65
|
+
|
|
66
|
+
To get the full report as JSON (for CI, dashboards or scripts):
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
pgshrink analyze "$DATABASE_URL" --table documents --column embedding --json > pgshrink.json
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## How it works
|
|
73
|
+
|
|
74
|
+
```mermaid
|
|
75
|
+
flowchart LR
|
|
76
|
+
A[(your table)] -->|"200 random rows<br/>as queries"| Q[queries]
|
|
77
|
+
A -->|"COPY ... BINARY<br/>whole column, streamed"| S[exact search<br/>on current vectors]
|
|
78
|
+
Q --> S
|
|
79
|
+
S --> T[true top-k<br/>per query]
|
|
80
|
+
A --> L["each layout:<br/>halfvec · subvector · binary_quantize<br/>± rerank"]
|
|
81
|
+
Q --> L
|
|
82
|
+
L --> C{same top-k<br/>as today?}
|
|
83
|
+
T --> C
|
|
84
|
+
C --> R[report + SQL]
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
1. **Queries.** About 200 random rows from your table serve as queries, and each one is excluded from its own results.
|
|
88
|
+
2. **Ground truth.** pgshrink streams the whole column with `COPY ... (FORMAT BINARY)` (about 700 MB for 171k × 1024 dims, read in ~6 s locally) and computes the exact top-k for every query. It compares against the full table on purpose: a sample would make reranking look better than it is, because 100 candidates cover far more of 5,000 rows than of 1,000,000.
|
|
89
|
+
3. **Layouts.** It reproduces in numpy exactly what pgvector computes (`halfvec` rounding, `subvector` truncation, `binary_quantize` signs, Hamming ranking, reranking on the original vectors). The integration tests check this against a real pgvector.
|
|
90
|
+
4. **Fidelity.** For each layout, it reports the share of the true top-k found in the layout's top-k, averaged over queries, with a bootstrap 95% CI.
|
|
91
|
+
5. **Recommendation.** It recommends the smallest index whose *lower* CI bound reaches `--target` (default 95%).
|
|
92
|
+
|
|
93
|
+
## Applying the recommendation
|
|
94
|
+
|
|
95
|
+
pgshrink prints the SQL but never runs it. **Try it on a copy or a replica first.**
|
|
96
|
+
|
|
97
|
+
**1. Build the new index next to the old one.** `CONCURRENTLY` doesn't block writes.
|
|
98
|
+
|
|
99
|
+
```sql
|
|
100
|
+
CREATE INDEX CONCURRENTLY IF NOT EXISTS documents_embedding_binary1024_idx
|
|
101
|
+
ON documents USING hnsw ((binary_quantize(embedding)::bit(1024)) bit_hamming_ops);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**2. Change your search query to use the same expression.** The planner only uses an expression index when the query matches it exactly. With reranking, fetch `k × rerank` candidates from the small index, then order them with the original vectors:
|
|
105
|
+
|
|
106
|
+
```sql
|
|
107
|
+
SET hnsw.ef_search = 100; -- must be >= the number of candidates
|
|
108
|
+
SELECT * FROM (
|
|
109
|
+
SELECT * FROM documents
|
|
110
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
|
|
111
|
+
LIMIT 100
|
|
112
|
+
) candidates
|
|
113
|
+
ORDER BY embedding <=> $1::vector(1024)
|
|
114
|
+
LIMIT 10;
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
In Python (psycopg 3 + pgvector):
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
from pgvector.psycopg import register_vector
|
|
121
|
+
|
|
122
|
+
SEARCH = """
|
|
123
|
+
SELECT id, title FROM (
|
|
124
|
+
SELECT id, title, embedding FROM documents
|
|
125
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize(%(q)s::vector(1024))::bit(1024)
|
|
126
|
+
LIMIT 100
|
|
127
|
+
) c ORDER BY embedding <=> %(q)s::vector(1024) LIMIT 10
|
|
128
|
+
"""
|
|
129
|
+
|
|
130
|
+
register_vector(conn)
|
|
131
|
+
with conn.transaction():
|
|
132
|
+
conn.execute("SET LOCAL hnsw.ef_search = 100")
|
|
133
|
+
rows = conn.execute(SEARCH, {"q": query_embedding}).fetchall()
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
In Node.js (`pg` + `pgvector`):
|
|
137
|
+
|
|
138
|
+
```js
|
|
139
|
+
import pgvector from 'pgvector/pg';
|
|
140
|
+
|
|
141
|
+
const SEARCH = `
|
|
142
|
+
SELECT id, title FROM (
|
|
143
|
+
SELECT id, title, embedding FROM documents
|
|
144
|
+
ORDER BY binary_quantize(embedding)::bit(1024) <~> binary_quantize($1::vector(1024))::bit(1024)
|
|
145
|
+
LIMIT 100
|
|
146
|
+
) c ORDER BY embedding <=> $1::vector(1024) LIMIT 10`;
|
|
147
|
+
|
|
148
|
+
await client.query('BEGIN');
|
|
149
|
+
await client.query('SET LOCAL hnsw.ef_search = 100');
|
|
150
|
+
const { rows } = await client.query(SEARCH, [pgvector.toSql(queryEmbedding)]);
|
|
151
|
+
await client.query('COMMIT');
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
**3. Check it on your traffic.** Run `EXPLAIN` on the new query and look for the new index. Then compare results against the old query for a sample of real searches.
|
|
155
|
+
|
|
156
|
+
**4. Drop the old index** once the new queries are live, to free its memory. To roll back, switch the query back; the old index is untouched until you drop it.
|
|
157
|
+
|
|
158
|
+
## Options
|
|
159
|
+
|
|
160
|
+
| option | default | meaning |
|
|
161
|
+
|---|---|---|
|
|
162
|
+
| `--table` | required | table name, optionally `schema.table` |
|
|
163
|
+
| `--column` | required | a `vector(n)` column |
|
|
164
|
+
| `--metric` | from the index | `cosine`, `ip` or `l2` |
|
|
165
|
+
| `--k` | 10 | top-k to compare |
|
|
166
|
+
| `--queries` | 200 | random rows used as queries |
|
|
167
|
+
| `--target` | 0.95 | minimum lower 95% bound of fidelity for a recommendation |
|
|
168
|
+
| `--max-rows` | 2,000,000 | rows scanned; above this a random subset is used (reported) |
|
|
169
|
+
| `--seed` | 0 | same seed, same queries and same results |
|
|
170
|
+
| `--json` | off | machine-readable report |
|
|
171
|
+
|
|
172
|
+
## Safety
|
|
173
|
+
|
|
174
|
+
- Every transaction is opened with `default_transaction_read_only = on`, and a test checks that writes fail.
|
|
175
|
+
- It reads the vector column and `ctid`, plus catalog metadata: column type, row estimate, index names and sizes. It reads no other columns.
|
|
176
|
+
- It writes nothing to disk and never logs the connection string.
|
|
177
|
+
- `statement_timeout` defaults to 5 minutes.
|
|
178
|
+
- On a managed database, scanning the column costs one sequential read of it. Run it against a replica if you can.
|
|
179
|
+
|
|
180
|
+
## What it does not tell you
|
|
181
|
+
|
|
182
|
+
- **Fidelity is not retrieval quality.** It measures "same results as today". If today's results are wrong, they stay wrong. That is also why it needs no labels.
|
|
183
|
+
- **The queries are your stored rows.** If your model embeds queries differently from documents (e5's `query:` prefix, instruction prompts), real queries may behave a little differently.
|
|
184
|
+
- **HNSW adds its own approximation** on top of compression: about −1 to −2 points in our validation. Raise `hnsw.ef_search` if you need it back.
|
|
185
|
+
- **Truncation (`subvector`) only makes sense for Matryoshka-trained models.** pgshrink measures it either way, and a large drop is the signal that your model isn't one.
|
|
186
|
+
- **The index size is an estimate** from a page-packing model fitted on real pgvector HNSW indexes (`m = 16`, within 3%). Other `m` values or index types (IVFFlat) are less precise.
|
|
187
|
+
- For now it supports `vector(n)` columns on pgvector 0.7+ (needed for `halfvec` and `binary_quantize`).
|
|
188
|
+
|
|
189
|
+
## Development
|
|
190
|
+
|
|
191
|
+
```bash
|
|
192
|
+
git clone https://github.com/alessandroamormino/pgshrink && cd pgshrink
|
|
193
|
+
uv sync
|
|
194
|
+
uv run pytest # unit tests
|
|
195
|
+
|
|
196
|
+
docker run -d --name pgshrink-test -e POSTGRES_PASSWORD=pg -p 55432:5432 pgvector/pgvector:pg17
|
|
197
|
+
PGSHRINK_TEST_DSN=postgresql://postgres:pg@localhost:55432/postgres uv run pytest # + integration tests
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
The integration tests run every printed SQL statement against a real pgvector. They check that it returns the neighbors that pgshrink's numpy model predicts, and that the connection really is read-only.
|
|
201
|
+
|
|
202
|
+
Issues and pull requests are welcome, especially reports of how the numbers compare with your production results.
|
|
203
|
+
|
|
204
|
+
## License
|
|
205
|
+
|
|
206
|
+
[Apache-2.0](LICENSE)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
pgshrink/__init__.py,sha256=UpoD_Jn6NuU-KduSHWoeKesjbvTZKK5m6iigcFqZMVY,116
|
|
2
|
+
pgshrink/cli.py,sha256=30c7x3q77wL07aTHW6C5eqrGqZsZ_jX9-JqN7QcYr94,5966
|
|
3
|
+
pgshrink/db.py,sha256=Xzm5OxLzMXJJN95zjJdNU-eqSdOyQFuWR5Q_4n6KoT4,5786
|
|
4
|
+
pgshrink/measure.py,sha256=sZOOTPvwwOQ9TA43jT4IqlUjSYVTI4teA44M-sEMlHA,5970
|
|
5
|
+
pgshrink/sql.py,sha256=etFY0aGHPkKGbXFBc1WwO-X3_C4KK2x5SGIZAK0wjZY,2092
|
|
6
|
+
pgshrink-0.1.0.dist-info/METADATA,sha256=LJtTEjnjB9GvLMMRYdOOcO7Deczg0cSB2aSoKmWRYj4,10097
|
|
7
|
+
pgshrink-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
8
|
+
pgshrink-0.1.0.dist-info/entry_points.txt,sha256=3fzddrY-7CW8Kzl8QKNMFGwae5kxarr8z8CliQvkbg4,47
|
|
9
|
+
pgshrink-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
10
|
+
pgshrink-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|