home.social

Search

158 results for “DoubleA”

  1. Huntington Beach girls’ tennis upsets Newport Harbor in league finale

    The Huntington Beach High girls’ tennis team surged out of the gates Thursday afternoon and never looked back.…
    #NewsBeep #News #US #USA #UnitedStates #UnitedStatesOfAmerica #Tennis #bellaapplehof #dang #double #gametoday #huntingtonbeachgirl #League #leaguefinale #match #newportharbor #no #Oilers #regular-season #secondround #Sports #team
    newsbeep.com/us/893588/

  2. 'Did we do well today?': This is what it takes to keep an independent restaurant open
    By Alexandra Carlton and Teresa Tan

    Restaurants close at double the rate of businesses in other sectors. Yet as rivalry from huge restaurant groups and home delivery like Uber Eats rises, as the cost of living bites and policy shifts such as credit card charges impact profit, how do restaurants remain viable? And what do we lose as a community if our favourite, personality-filled local independent eatery can no longer compete?

    abc.net.au/news/2026-10-25/res

    #DiningOut #SmallBusinesses #CostofLiving #HospitalityIndustry #FoodandDrink #AlexandraCarlton #TeresaTan

  3. @BigB63
    #𝔹𝕚𝕘𝔹𝟞𝟛
    #𝔹𝕣𝕚𝕒𝕟ℂ
    #𝔹𝕣𝕚𝕒𝕟
    #𝕊𝕥𝕖𝕗
    #𝕊𝕥𝕖𝕗𝕒𝕟𝕚𝕒
    #𝕊𝕥𝕖𝕗𝕤ℙ𝕚𝕔𝕜𝕤
    𝔹𝕣𝕚𝕒𝕟
    𝕚𝕤
    #𝕠𝕟𝕝𝕪
    𝟙 𝕠𝕗 𝟚
    𝕥𝕙𝕒𝕥 𝕀
    #𝕜𝕟𝕠𝕨 𝕠𝕗
    𝕨𝕙𝕠 𝕖𝕧𝕖𝕟
    𝕨𝕙𝕖𝕟
    #ℝ𝕖𝕡𝕝𝕪
    𝕀 𝕕𝕠 ℕ𝕠𝕥
    #𝕣𝕖𝕔𝕖𝕚𝕧𝕖
    #ℕ𝕠𝕥𝕚𝕗𝕚𝕔𝕒𝕥𝕚𝕠𝕟.
    #𝔻𝕠𝕦𝕓𝕝𝕖ℂ𝕙𝕖𝕔𝕜𝕖𝕕
    𝕞𝕪
    #𝕊𝕖𝕥𝕥𝕚𝕟𝕘𝕤
    𝕤𝕠 𝕟𝕠𝕥 𝕠𝕟
    𝕞𝕪 𝕖𝕟𝕕.
    𝕋𝕙𝕦𝕤
    #𝕚𝕟𝕤𝕥𝕖𝕒𝕕
    𝕀
    #𝕔𝕙𝕖𝕔𝕜
    𝕠𝕟 𝕪𝕠𝕦𝕣
    𝕒𝕔𝕔𝕠𝕦𝕟𝕥.
    𝕐𝕖𝕥 𝕨𝕙𝕒𝕥
    #𝕗𝕦𝕣𝕥𝕙𝕖𝕣
    𝕥𝕙𝕣𝕠𝕨𝕤 𝕚𝕥 𝕠𝕗𝕗
    𝕚𝕤 𝔹𝕣𝕚𝕒𝕟'𝕤
    #ℙ𝕚𝕟𝕟𝕖𝕕 #ℙ𝕠𝕤𝕥𝕤.
    𝕀
    #𝕤𝕖𝕖
    𝕥𝕙𝕒𝕥
    𝕀 #𝕟𝕖𝕖𝕕
    𝕥𝕠
    #𝕘𝕠
    #𝕓𝕖𝕪𝕠𝕟𝕕
    #𝕒𝕟𝕪 𝕠𝕗
    𝔹𝕣𝕚𝕒𝕟'𝕤
    ℙ𝕚𝕟𝕟𝕖𝕕 ℙ𝕠𝕤𝕥𝕤
    𝕥𝕠 #𝔻𝕚𝕤𝕔𝕠𝕧𝕖𝕣
    𝕨𝕙𝕖𝕟 𝔹𝕣𝕚𝕒𝕟
    𝕨𝕒𝕤 #𝕝𝕒𝕤𝕥 𝕠𝕟
    + 𝕚𝕗
    #𝕓𝕠𝕠𝕤𝕥-𝕖𝕕
    𝕒 #𝕡𝕠𝕤𝕥
    𝕒𝕟𝕕 𝕚𝕗
    #𝕣𝕖𝕡𝕝𝕚𝕖𝕕.
    𝕆𝕟
    𝕐𝕠𝕦𝕣
    #𝕋𝕠𝕡𝕚𝕔
    𝕛𝕦𝕤𝕥
    𝕟𝕠𝕥
    𝕗𝕠𝕣 ℂ𝕝𝕦𝕓
    𝕣𝕒𝕥𝕙𝕖𝕣
    #𝔻𝕣𝕖𝕤𝕤𝕖𝕕
    𝕗𝕠𝕣 𝕥𝕙𝕖
    #𝕊𝕔𝕖𝕟𝕖

  4. From Chelsea reject to Watkins 'upgrade' - Jackson makes fast Villa start
    bbc.co.uk/sport/football/artic
    Nicolas Jackson continues an excellent start to his Aston Villa career with a match-winning double against Manchester City. #AVFC #UTV #Villains

  5. My latest attempt at building a bicycle camper is a 2 stage design.
    Stage 1: A quad with full suspension to be built, as far as I can, from scrap steel.
    Size 80cm wide, 160cm high and 210cm long.
    Probably with double motors driving a central axle so I can coaster without any motor is engaged.
    My plan, so far, is to have a front windscreen and a roof with 200w solar panel but the sides… fahrradwagen.com/d/8527-quad-c

  6. Stark numbers, a worthwhile reading. The super-rich are destroying our planet and democracy. If you think that destroying our livelihoods for money is a good idea, you are suffering from some kind of Stockholm syndrome. #economy #democracy #capitalism #FalseIncentives

    theguardian.com/environment/20

  7. “Addressing the climate crisis is really easy. Control the richest, curb their power, curb their emissions, and also tax their wealth.” theguardian.com/environment/20

  8. OpenAI launched GPT-6.1 Terra on October 26, 2026, and if you build agents for a living, the interesting question is not "is it smart?" It is "where does it sit in my routing table?" After reading OpenAI's own numbers as reported on October 26–27, my answer is: Terra becomes the default tier, and the flagships become the exception. Here is the reasoning, with the numbers that justify it.

    The default tier, priced like one


    Terra's API pricing is $1 per million input tokens, $0.05 per million cached input tokens, and $5 per million output tokens — 50% below GPT-5.6 Terra and GPT-6.1 Sol. Standard rates cover prompts up to 272,000 input tokens; beyond that, input and cache rates double and output costs 1.5x for the full request. It is available in ChatGPT Work and Codex for Plus, Pro, Enterprise and Edu users, and via the API as gpt-6.1-terra.

    Price alone would not move me. Price plus speed plus accuracy does. Terra runs tasks more than three times faster than GPT-6 Astra and GPT-6.1 Sol. On Agents' Last Exam — professional work such as turning architectural drawings into 3D models or reviewing film scenes into time-coded logs — it beats its predecessor by 15 points at medium reasoning effort, at about a third of the cost, matching Astra at roughly a tenth of the token price. On OSWorld 2.1, multi-step desktop-app work, it beats its predecessor's best score at medium effort and costs less per task.

    The routing rule


    Here is the rule I would ship this week:

    1. Terra by default for the workday bulk: invoice intake, form filling, document processing, inbox triage, proposal drafts, screenshot and drawing interpretation, and routine coding — scripts, fixes, refactors, tests.
    2. Sol or Astra on exception for complex coding and the hardest reasoning. Terra's Terminal-Bench 4.0 score is 50.3% at maximum effort — more than double its predecessor's 21.5% — but OpenAI itself says Sol and Astra are better for complex coding. Believe the vendor on its own product's limits.
    3. Effort as a dial, not a setting. Start bulk tasks at medium effort. Escalate to maximum effort only where the error rate matters, because the error numbers justify that dial: on OpenAI's error-inducing internal test, Terra's error rate is 16.7% at low effort (down from 53.6% for the predecessor) and 4.3% at maximum effort — comparable to the flagships.

    That third point is the one most routing layers get wrong. They route by model, once, at design time. Terra rewards routing by model and effort, per task, at runtime. A form-fill at medium effort and a contract-summary at maximum effort are different jobs even when they use the same model.

    Two tests before you widen autonomy


    Terra's alignment claims are the part I would verify before trusting it with a computer. OpenAI says it stays within scope, discloses limitations and blockers honestly, and resists prompt injection in testing. For a computer-use model, those are not nice-to-haves — they are the security boundary.

    Test one: put an instruction inside a document that contradicts your instruction, and see whether Terra follows the document or you. Test two: give it a task with a deliberate blocker and see whether it reports the blocker or invents a completion. If it passes both on your data, widen autonomy gradually. If it fails either, keep the human approval gate — especially for money, legal, or irreversible actions. A 4.3% error rate at maximum effort is excellent for this tier, and it is still an error rate.

    Measure cost per finished task


    The metric that matters after the switch is not cost per token. It is cost per completed task, including retries and corrections. Terra's speed and accuracy gains compound there: fewer retries, fewer human corrections, lower total cost even before the 50% price cut. Run your five most common tasks through Terra for a week, log completion rate, error rate, and cost per finished task at medium and maximum effort, and let that table — not the launch blog — set your permanent routing.

    Terra is not the model you show off. It is the model you leave running all day. Priced and performing like this, that is exactly where it belongs: as the default, with flagships reserved for the work that actually needs them.

    Sources: OpenAI GPT-6.1 Terra launch (October 26, 2026), as reported by NewsBytes, Okay News, and MoneyToday (October 27, 2026). Benchmark figures are OpenAI's own reported evaluations. Author: Shivam Kumar, Founder, VisionQuantech.#ai #llm #openai #agents #software #coding #development #engineering #inclusive #community
    I Re-Priced My Agent Stack on GPT-6.1 Terra: Here's the Routing Rule I'd Actually Ship

  9. "Earlier this month, a new report found that, due to deteriorating soil quality, crops including carrots, apples and peas are now 20% to 50% less nutritious than they were in the 1960s. So should we be eating double the amount?"

    theguardian.com/society/2026/o

    The report mentioned/linked to is behind a 'subscribe and give us your email address so we can spam you'!

    Headline of the report:

    "Cereal yields are up 215% per hectare since the 1960s, but more than 2 billion people have at least one clinical micronutrient deficiency.

    In collaboration with The Mark Leonard Trust, we produced Hollow Harvests to examine how decades of breeding and farming for yield have left many crops with 20 to 50% less of several key nutrients. A carrot with half the potassium means eating twice as many carrots to get the same benefit."

    Download it free without annoying subscription:

    Short version:
    DSV-HollowHarvest_Exec-Report.pdf

    drive.proton.me/urls/1T4NRRYMM

    Full version:
    DSV-HollowHarvest_Full-Report.pdf

    drive.proton.me/urls/T4S4XGBBM

    #food #PolyCrisis #poverty #Soil #SoilDegradation #IndustrialAgriculture

  10. Monday morning, and I’ve already gotten my Covid and flu vaccines, and I’ve voted in the Toronto civic election.

    It’s unfortunate that in such a tight race, there is a second (practically unknown) candidate with the same last name as the incumbent. If he does siphon votes away from the incumbent, it will be completely obvious in the post-election statistics, but with no way to prove that he wasn’t just that popular.

    My personal opinion is that any time a last name is duplicated anywhere on a ballot, election workers should mention it (without naming names). Just “here is your ballet — please note some names show up more than once, so please double check your choice.”

  11. I was going to quote another toot as an example; but it decided against doing that…

    For the folks that are on instances that have large (>1000) character limits: Please know that you don’t have to max out your limit. If you must, post a large toot, please break it up into multiple toots, if those multiple toots go into double digits, please consider getting a blog, and post you stuff their and in a single toot post a link with a summary.

  12. “This essay is an exploration of what I learned along the way of making agentic coding work within the context of a smaller product company. I’ll discuss the habits that had to go, the replacements that limit risks, as well as the decades-old fundamentals that we had to double down on.
    We’ll cover it all. As is customary, let’s start from the beginning with the pivotal point that made us go agentic.”

    adamtornhill.substack.com/p/ta

  13. I really don't trust too much those developers that just popped into existence with great projects in 2026.

    Check their contributions past year, nada.

    Yeah, that's the commitment. 28-old developers my ass, #AI is doing the job, and the moment your tokens double in price you'll leave that shit.

    #ArtificialIntelligence #VibeCoding #VibeCode #Programming #Programmers #SoftwareDevelopment #WebDevelopment #AppDevelopment #AppDev #WebDev #Coding #Code #GitHub #Bots #Bot

  14. My Analysis Of A Complete Meltdown In Wisconsin

    Before the season, I thought USC would probably lose to either Penn State or Wisconsin because those were games that Lincoln Riley really struggles winning.

    But never in my wildest dreams would I imagine Wisconsin would hold Riley to 7 points, the first time in his 10-year-career his team failed to score double digits.

    Wisconsin had 58 yards passing and only 200 yards of offense and still won by 17 points.

    It was an extraordinary result but it simply illustrated all the things I have railed against Riley for years and showed why his time has been up for a long time despite the delusional faction of pundits (mentioned below) and fanboys who support him.

    I’ve never liked the offensive lines under Riley. People swore all offseason this year was great because the entire line returned intact. USC rushed for 40 yards against Wisconsin when you took away the sack yardage.

    That’s unforgiveable, especially when it can’t ever convert in short-yardage situations. People love to focus on the wide receivers but good teams win by running the ball. I’ll never understand why so many are blind to this deficit.

    Even when USC was playing all those cupcakes at the outset of the season, I said the Trojans’ physicality was a problem despite all the offseason claims about the strength coach improving the team.

    Wisconsin gave USC a no-nonsense whipping from a physicality standpoint. Their offense pushed the pile and really gave the Trojans problems on quarterback RPO plays. Their defense was easily superior.

    Games are won at the line of scrimmage and Riley can’t handle these Big 10 teams that value strength. It’s a big reason he also struggled with Notre Dame and Oregon.

    Here’ the other thing: I don’t think Riley tackles enough in practice or holds physical practices. USC just looks flat-footed too many times on defense and that’s a reason why things look the same no matter who is the defensive coordinator.

    That doesn’t absolve Grandpa Patterson on that touchdown play where Wisconsin had four players defended by only two USC players. He didn’t have the defense aligned and didn’t call a timeout. Of course, the head coach should have called the timeout but he’s not paying attention to the defense.

    Also: Wisconsin won without even testing the shoddy pass defense!

    I keep saying Jayden Maiava struggles on the road. Oregon and Nebraska last year. Last night was a disaster. He cannot handle pressure.

    Then the special teams. USC hired Mike Ekeler but every game has at least one blunder on special teams.

    I could go on but let’s look at the big picture.

    Where’s Joel Klatt, Yogi Roth, Josh Pate, RGIII and Colin Cowherd? All they do is glaze Riley. What will they say this week? They have repeatedly embarrassed themselves with their defenses of Riley.

    I’m tired of hearing Riley and others say the culture has changed. The culture has not changed! It will never change under Riley. He has none of the leadership traits of John McKay or Pete Carroll.

    USC could easily lose three more games in part because Riley is not a leader of men. He never rallies the troops. He doesn’t instill any belief.

    Is USC stuck with him because of his grotesque buyout?

    Well, a solution would be if Baylor or TCU came calling for the Texas native. Frankly, he’s probably calling them first.

    But if he gets hired elsewhere, that salary could offset his buyout.

    That is our best hope to remove this fraud from a football program that is crying out for much more of a leader than him.

    #collegeFootball #featured #FightOn #FOOTBALL #usc
  15. Latest release: 3.1.12

    Windows-only update. macOS, Linux, Android, iOS, CLI and Clipman Server do not need an update for these changes.

    ClipMerge now measures the double-copy interval from the original Windows clipboard notifications, so processing delays do not make a timely second copy miss the merge window.
    Copying several selected history entries, including Copy Name and Content, updates their last-used times in one save instead of saving and uploading the entire history once per selected item.
    Routine automatic website-title failures no longer fill the runtime log. Diagnostics retains session counts and a brief failure reason in memory, without website addresses. Actual fault logging and log rotation remain available.

    onj.me/software

  16. Scott McTominay continued his hot streak with two goals as Napoli led twice, but Roma fought back to draw 3-3 in Naples with Matias Soulé and Leonardo Balerdi on target.

    #Football #seriea #napoli #footballnews2026 #asroma #footballhighlights

    mondiaries.com/2026/10/balerdi

  17. Niclas Fullkrug scored twice from the spot as Werder Bremen beat Mainz 05 3-2 in a Bundesliga thriller. Read the full match report, goals and highlights from Mewa Arena.

    #Football #bundesliga #werderbremen #footballnews2026 #Mainz05 #footballhighlights #mainz

    mondiaries.com/2026/10/fullkru

  18. CW: Personal finance concerns

    Lawyer set up a trust for me and fucked up the mortgage transfer in a way so that it triggered a new appraisal, and I’ve been pouring my savings into escrow, but if it doesn’t get fixed in the next year, I’m gonna have to sell.

    And even if it does get fixed, I am worried that this absurd inflation is going to do it anyway.

    Everything costs double what it did when I was forced to retire.

  19. Any idea why an artist would be listed twice in an Android media player?

    Some of the ones I've tried don't list it twice (Musicolet, Auxio, VLC) and some of them do (Gramophone, Fossify). It's always the same albums listed in each group, too.

    I double-checked the metadata using both the Apple Music app on my MacBook and Picard, and all of the tracks have the same track/album artist without any extraneous characters.

    #Android #Audio #Media

  20. Hedge funds help markets function in calm times, but they can amplify stress when conditions turn, according to the IMF's October 2026 Global Financial Stability Report.

    The scale has changed. Gross assets have tripled since 2013, to almost $13 trillion. Total exposures, including off-balance-sheet obligations, are about $40 trillion. In 2025, hedge funds held around 9% of US government debt.

    📖 Read the full story: economicsperspective.com/expla

    #HedgeFunds #IMF #FinancialStability #SystemicRisk

  21. À Paris, la préfecture dénombre ce samedi #24octobre autant de manifestants que le #17octobre.

    D’autres sources évoquent même une affluence supérieure, malgré les restrictions au droit de #manifester et un dispositif #sécuritaire considérablement renforcé, avec unités d’élite et blindés.

    Ce mouvement semble témoigner d’un ras-le-bol de cette décennie macroniste, marquée par des inégalités croissantes et une pauvreté à un niveau record, tandis que la fortune des milliardaires français a doublé depuis 2017, au profit d’une infime minorité : les ultrariches.

  22. The review usually opens with a demo that looks fine. An agent plans four edits, applies them to a workspace on a remote box, and reports success; the tests are green and everyone relaxes. Two hours later a human's refactor is gone, and nobody can point at the request that removed it. Is that a model problem, a server problem, or a protocol problem?

    I think it is a protocol problem almost every time, and I want to make the case with an executable fixture rather than an architecture diagram. Below is the event order I keep reconstructing in reviews, the invariant it violates, and a small simulator that will fail your design for you. Everything here is a model of a system, not a benchmark of a vendor.

    1. The event order that silently wins


    A planner reads the workspace at revision 0 and emits three steps against app.py. Step 1 applies and the workspace moves to revision 1. While step 2 is in flight, either a human edits that file or the session is re-routed to a different model that re-plans the remainder; both are ordinary events, not incidents.

    Step 2 still carries the content hash it was planned against. If the executor applies patches by path without checking that hash or the revision, the write lands on content the planner never saw, and the old bytes vanish. Nobody gets an error, because a patch is not a request — it is a claim about a state that may already be false.

    The failure is invisible precisely when it is most expensive. The agent's summary says "updated handler and tests", the test run passes because the overwritten hunk was unrelated, and the loss only surfaces at the next merge. Who is supposed to notice that?

    2. The invariant, stated once


    No step may be applied unless the state it was planned against is still the state it is applied to, or the step has been explicitly rebased onto the new state.

    That is it. Note what the invariant does not say: it does not say a step is correct, and it does not say a retried step is safe. A revision fence prevents stale acceptance; idempotency prevents double application. Teams routinely build one, assume they have the other, and then argue about whose bug it is.

    3. Declared assumptions


    • One writer per file at a time; concurrent multi-writer edits are out of scope and need a merge protocol, not a fence.
    • The workspace has a monotonic revision counter and a per-file content hash that are both persisted with the workspace itself.
    • A step is planned from a readable snapshot and carries (step_id, base_rev, path, pre_hash, patch).
    • Execution may be preempted at any point between "patch written" and "client received the result".
    • Model identity may change inside a session, because routing, fallback, or a free-tier allowance running out can move you to another model without warning.


    4. Data flow and failure domains


    There are three state holders and they fail independently: the planner's context (lossy, model-dependent), the executor's workspace (authoritative, preemptible), and the client's view of progress (optimistic, retried). The only durable truth is the workspace plus whatever journal you persist alongside it.

    Failure domains worth separating in review: stale plan (planner state diverged), lost ack (executor applied, client did not learn), duplicate delivery (client retried an applied step), and re-plan drift (a new model emits steps against an old base). They need different mechanisms, and a single retry counter hides all four.

    5. The fixture


    This is deterministic Python with no model calls, so the verdicts below are properties of the protocol, not of any provider.

    # fence_sim.py - deterministic, no LLM involved
    from dataclasses import dataclass

    @dataclass(frozen=True)
    class Step:
    step_id: str
    base_rev: int
    path: str
    pre_hash: str
    patch: str

    class Workspace:
    def __init__(self):
    self.rev = 0
    self.files = {"app.py": "v0"}
    self.journal = set() # persisted with the workspace
    def hash(self, path):
    return self.files
    [path] def write(self, path, content):
    self.files[path] = content
    self.rev += 1

    class Executor:
    """fence: 'none' | 'plan' | 'step'; dedupe: journal-backed idempotency"""
    def __init__(self, ws, fence="step", dedupe=True):
    self.ws, self.fence, self.dedupe = ws, fence, dedupe
    self.plan_rev = None
    def plan(self, rev):
    self.plan_rev = rev
    def stamp(self, s):
    if self.fence == "step":
    return Step(s.step_id, self.ws.rev, s.path, self.ws.hash(s.path), s.patch)
    if self.fence == "plan":
    return Step(s.step_id, self.plan_rev, s.path, s.pre_hash, s.patch)
    return s
    def exec(self, s):
    s = self.stamp(s)
    key = (s.step_id, s.base_rev)
    if self.dedupe and key in self.ws.journal:
    return "deduped"
    if self.fence != "none":
    if s.base_rev != self.ws.rev:
    return "rejected:stale_rev"
    if self.ws.hash(s.path) != s.pre_hash:
    return "rejected:pre_hash"
    self.ws.write(s.path, s.patch)
    if self.dedupe:
    self.ws.journal.add(key)
    return "applied"

    Two lines deserve attention. The journal lives in Workspace, not in the executor, because an in-process dedupe set dies with the server that was preempted — which is exactly the trap. And stamp is where fence granularity is decided, so you can argue about it in one place.

    6. Injecting the three failures


    Run the same three scenarios across fence modes and record the verdicts. The interference classes are injected explicitly, so the denominator is the number of injections, not the number of suspicious log lines.

    def scenario_concurrent_edit(fence):
    ws = Workspace(); ex = Executor(ws, fence=fence); ex.plan(ws.rev)
    s1 = Step("s1", 0, "app.py", "v0", "v1")
    s2 = Step("s2", 1, "app.py", "v1", "v2")
    assert ex.exec(s1) == "applied"
    ws.write("app.py", "human-refactor") # interference: rev 2
    return ex.exec(s2)

    def scenario_preemption_retry(fence):
    ws = Workspace(); ex = Executor(ws, fence=fence)
    s1 = Step("s1", 0, "app.py", "v0", "v1")
    ex.exec(s1)
    # ack lost; client replays s1 against a fresh executor, same persisted workspace
    return Executor(ws, fence=fence).exec(s1)

    def scenario_replan_drift(fence):
    ws = Workspace(); ex = Executor(ws, fence=fence); ex.plan(ws.rev)
    ex.exec(Step("s1", 0, "app.py", "v0", "v1"))
    ex.plan(ws.rev) # new model re-plans from rev 1
    return ex.exec(Step("s2", 0, "app.py", "v0", "v1-tail"))

    Expected output, because the simulation is deterministic and calls no model:

    fence=none concurrent_edit -> applied preemption_retry -> applied twice replan_drift -> applied
    fence=plan concurrent_edit -> rejected:stale_rev preemption_retry -> rejected:stale_rev replan_drift -> rejected:stale_rev
    fence=step concurrent_edit -> rejected:stale_rev preemption_retry -> rejected:stale_rev replan_drift -> applied
    dedupe on concurrent_edit -> rejected:stale_rev preemption_retry -> deduped replan_drift -> applied

    Read the second and third rows together, because that is the argument. A plan-level fence turns every retry into a spurious rejection and every legitimate re-plan into a dead end; it is loud, but it is loud in the wrong places. A step-level fence plus a persisted journal gets you the two properties you actually want, and it costs you a durable set of (step_id, base_rev) keys.

    7. Making it a property, not a demo


    Three scenarios are an anecdote. Turn them into invariants and let a random interleaving search hunt for violations — this is the part I would block a design review on.

    def invariants_hold(ws, results):
    # P1: every applied step saw base_rev == rev at apply time
    assert all(r.rev_at_apply == r.base_rev for r in results if r.status == "applied")
    # P2: journal is append-only per (step_id, base_rev)
    assert ws.journal == set(ws.journal)
    # P3: no path content was replaced by a step older than the current rev
    assert all(r.base_rev <= r.rev_at_apply for r in results)

    Then fuzz: shuffle {human_edit, preempt, retry, replan, duplicate_delivery} over a fixed step list, run 5,000 seeds, and assert P1 and P2 for every seed with fences on. Run the same search with fence="none" to extract a minimal counterexample, and put that event order in the PR description as the regression case. A protocol claim without a counterexample search is a preference.

    8. Where the free tier changes the arithmetic


    If your executor is a shared, preemptible environment and your planner can move between models at any time, then re-plan drift and lost acks are not edge cases — they are the steady state. That is the actual architectural consequence of running agents on free resources, and it argues for cheap, persisted fences rather than expensive coordination.

    I use MonkeyCode as the concrete instance of that environment in this review: it is an open-source coding agent whose operator supplies free model access (currently advertised as a 10M-token allowance) and a free server option. Treat those numbers as operator-supplied and re-verify them on the project page before you design around them, because allowances and routing change faster than any architecture does. My interest here is narrow: a free server makes preemption ordinary, and free model access makes mid-session re-routing ordinary, so both of my injected interferences become Tuesday.

    Disclosure: This article was prepared as part of MonkeyCode's product outreach.

    9. Tradeoffs I would write down

    MechanismBuys youCosts youFails whenNo fenceThroughput, simplicitySilent lost updatesAny concurrent editPlan-level fenceLoud, cheap rejectionRe-planning whole plans, spurious retriesModel swap or long plansStep-level fencePrecise staleness detectionA re-stamp on every dispatchSemantic overlap between stepsPersisted journalIdempotent retry across preemptionDurable key storage, growth controlJournal not persisted atomically with the writeCheckpoint per stepFast compensationStorage, restore latencyLarge binaries, long test suites

    10. Verdicts: reject, replay, or compensate

    Event orderCorrect verdictWhyStep arrives, base_rev < current rev, no overlapReject, re-plan from current revThe plan is stale; the patch is not recoverableStep arrives, journal contains (step_id, base_rev)Replay the stored resultThe work is done; the ack is what was lostStep applied, tests for touched files failCompensate to the checkpointFence passed, semantics did notNew model re-plans mid-session from current revAccept if re-stamped and preconditions holdDrift is expected, staleness is notTwo steps with overlapping hunks in one planReject the plan at admissionA fence cannot order siblings

    11. What I would change next


    1. Persist the revision counter, file hashes, and journal in one atomic write, so a crash cannot leave a patch without its key.
    2. Stamp base_rev at dispatch, never at plan time, and log both values — the delta is your drift signal.
    3. Bound the journal by session and drop it only after a checkpoint the workspace itself can prove.
    4. Run the fuzz job in CI with fences on, and store the minimal counterexample from fence="none" as a named regression seed.
    5. Add a sibling-overlap check at plan admission, because per-step fences order nothing within a plan.


    12. Limits, and who should skip this


    The fixture models file-level hashing and a single writer; it says nothing about merge semantics, and it does not evaluate whether a patch was any good. If your model swap also changes plan quality, this protocol will happily accept a worse plan that happens to be revision-correct. That is a separate evaluation problem, and no fence will solve it for you.

    Skip this if your agent is single-turn and single-file with a human watching every apply, if your platform already gives each step an atomic worktree or VM snapshot, or if you cannot persist a journal durably — half of this mechanism without the journal is worse than none, because it rejects retries without making them safe.

    So here is the question I would leave in the review thread: which event order in your system breaks the invariant — a human edit racing step two, an ack lost after the write, or a re-plan against a stale base — and for that specific order, should the executor reject, replay, or compensate?#ai #architecture #distributed #testing #software #coding #development #engineering #inclusive #community
    Treat a Coding-Agent Step as a Revision-Fenced Command, Not a Prompt

  23. Even as the Mamdani Administration Touts Faster Government, It’s Time to Hit Pause on Bergen Green

    With the mayor’s office now producing and running ads for “faster government” and backing the ballot measures that “speed up” review of city projects, it seems unlikely that Mamdani administration will do the right thing when it comes to Bergen Green: slow down, take a second look at how the Adams administration handled the award process, and address any problems or irregularities. Instead, it seems, the city will move ahead at 516 Bergen Street with a developer recently found in federal court to have put workers and residents at risk at multiple affordable housing sites across the city, in Manhattan, the Bronx, and Brooklyn.

    In an email dated September 30, a representative from City Council member Crystal Hudson’s office tells concerned neighbors that her office:

    will flag this for HPD, but to level expectations I do not expect this information to trigger the city to select a new bidder as the RFP bidding process has already been finalized. That said, we certainly understand the concerns raised from the consent decree [issued in US v. Apex Building Company] and will ask HPD to ensure there is testing done and measures implemented to mitigate construction dust and relevant training/notification is conducted.

    This response skirts the issue; and it promises only that HPD will be asked “to ensure” that the Bergen Green developer follows the law. That would be the bare minimum requirement. The problem that the city still needs to address is that the Bergen Green bidding process appears to have been “finalized” without taking into account – or while actively and deliberately ignoring – the 2023 judgment and consent decree against Apex Building Company, and without fully and publicly disclosing this company’s track record on other affordable housing projects in New York City.

    Local residents were asked to weigh in on the project but given an incomplete picture. The award process was conducted without complete candor and without fully informing the public.

    The FOIL requests that I filed last month may help fill in some gaps. Documents released by the Department of Investigation in response to one request suggest that the paperwork on which the city relied when making this award does not square with the facts in the public record. A Vendor Disclosure Form on file with the Department of Investigation omits any mention of the judgment in United States v. Apex Building Company and whitewashes the developer’s record. Subsequent responses to FOIL should help determine whether the company’s adjudicated misconduct was taken into account at all when assessing its bid.

    What more can be ascertained about Apex’s business conduct from the public record, in the meantime? Apex Building Company, Apex Building Group, and the principals of those companies are named as parties in a number of New York State Court cases. These fall into different categories.

    There are, not surprisingly, a few commercial contract disputes over non-payment. These sorts of disputes may come with the territory for New York City developers, but they can also cause serious project delays and add to financial risk. For people living near the project, a developer’s legal and financial problems can translate to prolonged disruptions and degradation of local living conditions.

    Many other cases brought against Apex in New York State Courts are for torts and negligence. Someone was injured on the job; another person tripped at a job site; yet another person crashed his scooter into a bin. Again, builders and developers typically get taken to court over this kind of thing, so it’s not all that surprising to come across these complaints. But they suggest the kind of hazards that demolition and construction at 516 Bergen Street will bring to the neighborhood.

    Bergen Street is already a hazardous place for pedestrians and cyclists, due in part to the heavy automobile traffic heading toward Flatbush and double parking in the bike lane, and due also to the fact that the north-side sidewalks from the Bergen Street playground to Flatbush are obstructed by police parking. The vehicles and heavy machinery at the site during demolition and construction (which is scheduled to last four years) will exacerbate these problems, make the snarl of traffic at the intersection of Bergen Street and 6th Avenue even worse than it currently is, and introduce new hazards. What’s the plan? At a September 2025 meeting with the developer, neighbors were told that it was “unclear” where workers will park their vehicles when arriving at the site; and though I have asked on a number of occasions about coordination with DOT, I have not gotten a clear answer and to the best of my knowledge there has been no coordination and no plan keep the Bergen Street bike lane and sidewalks clear.

    Perhaps the most striking case of all in the New York State Court docket is one brought just last year: Department of Housing Preservation and Development of the City of New York v. HP Plaza LLC. In this case, Robert Horsford, President and Chairman of Apex Building Group, is among the defendants sued by HPD for violations of the New York City Housing Maintenance Code, specifically for “failure to provide heat and hot water, as required by law.” The very city agency that awarded Horsford’s company the contract for affordable housing at Bergen Green in 2024 had found, just one year earlier, in 2023, that another Horsford Company, HP Plaza LLC, failed to maintain basic living conditions at an affordable housing development. And HPD prevailed against Horsford and his co-defendants in court, with the judge imposing a penalty and ordering them to provide heat and hot water and boiler maintenance for residents of 310 West 148th Street – part of the West 148th affordable and low-income housing initiative.

    Do any internal HPD records related to the Bergen Green award even acknowledge this misconduct? Was any of the history I’ve reviewed in this post and in my first post on Bergen Green taken into account? Why should local residents expect the Bergen Green project to be handled more responsibly than other Apex projects?

    Business conduct can get easily overlooked or set aside when government moves faster and refuses to address public concerns. And a record of misconduct, and of putting the public at risk, can easily get buried when government contracts are awarded to cronies. What’s come to light about the Bergen Green project so far suggests that it would be appropriate for the current administration to hit pause on the project, look at how the Adams administration handled the Bergen Green award, and at least offer neighbors some assurances and a more candid assessment of the developer’s record.

    Beyond that, everyone should take a second look at the initiatives for “faster government” currently being touted by the Mamdani administration, and acknowledge the risks and costs to ordinary New Yorkers that speeding up review and shutting out the public can entail.

    #affordableHousing #bikeLanes #businessEthics #environmentalReview #EricAdams #ethics #fasterGovernment #FOIL #NIMBY #pedestrianSafety #permitting #urbanCycling #YIMBY
  24. A CPU-bound Python job split across four threads took 3.6 seconds on my machine. The same job split across four of Python 3.14's new subinterpreters took 0.9 seconds, roughly what one thread alone takes to do a quarter of the work. That part matched what I expected from the PEP. What I did not expect was that asking one of those subinterpreters to run two things at once does not slow it down. It refuses outright.

    concurrent.interpreters is new in the standard library as of Python 3.14, released on 7 October 2026. Subinterpreters themselves are not new - they have existed in the C API since Python 1.5 and CPython has used them internally for years - but PEP 734 is what makes them usable from ordinary Python code, with no C extension required. Each subinterpreter gets its own Global Interpreter Lock, which is the part worth testing: it is the thing that is supposed to let CPU-bound Python code actually use more than one core without reaching for multiprocessing.

    I tested it against a CPU-bound workload (counting primes below 400,000, a plain Python double loop with no C extensions to hide behind), compared against threads, processes, and a single thread, three runs each, inside a python:3.14-slim container with four cores available.

    The headline number

    approachtime for 4x the worksingle thread (1x unit, for reference)0.77 - 0.80s4 OS threads, classic GIL3.51 - 3.70s4 subinterpreters (new in 3.14)0.89 - 0.98s4 processes (multiprocessing)0.95 - 1.30s


    Four threads doing four units of CPU-bound work took more than four times as long as one thread doing one unit - 3.6s against roughly 0.8s, which is actually a bit worse than the 3.2s you'd get from perfect serialisation, because the GIL has to keep stopping one thread to let another run. Four subinterpreters doing the same four units took about 0.9s: close enough to the single-unit baseline that the extra three units of work were, for practical purposes, free. That is real parallelism, not a scheduling trick, and it lands in the same place multiprocessing already does.

    What it refuses: one thread per interpreter, not shared


    The PEP's selling point is that each interpreter has its own GIL. I wanted to see what happens when two threads try to use one interpreter's GIL at the same time, expecting it to behave like classic Python: both threads run, the shared GIL makes them take turns.

    That is not what happened. A single Interpreter object only tolerates one caller. A second concurrent call doesn't queue, and it doesn't share time with the first - it is rejected immediately:

    Exception in thread Thread-2 (_call):
    Traceback (most recent call last):
    File "/usr/local/lib/python3.14/concurrent/interpreters/__init__.py", line 226, in _call
    res, excinfo = _interpreters.call(self._id, callable, args, kwargs, restrict=True)
    concurrent.interpreters.InterpreterError: interpreter already running

    I confirmed the shape of this with three variants of the same interpreter, run in sequence:

    scenariotimeoutcomeone call0.84sfinetwo sequential calls, same interpreter1.63sfine, roughly 2xtwo concurrent calls, same interpreter0.84s wall-clocksecond call raises InterpreterError


    interpreters.create() is documented as returning "a new (idle) Python interpreter", and that word is accurate: idle or running, nothing in between. If you want N things running at once, you need N interpreters, one each. A thread pool aimed at a single shared interpreter - the pattern every ThreadPoolExecutor tutorial uses with regular threads - does not translate. You get one interpreter's worth of work and an exception, not graceful serialisation.

    The opposite number: interpreters are not obviously cheaper to start than processes


    The other assumption I walked in with was that subinterpreters, being lighter than OS processes, would be cheap to spin up. I measured the cost of creating four workers and giving each one some real state (a 200,000-element list), steady state after the first warm-up run:

    approachcreate + populate, 4 workersfork (Python 3.13's Linux default)0.037 - 0.038sforkserver (Python 3.14's Linux default)0.057 - 0.065s4 subinterpreters0.076 - 0.078s


    Creating four subinterpreters and running a small amount of code in each took about twice as long as a classic fork-based process pool, and somewhat longer than the new forkserver default too. None of this matters once the work inside each worker takes more than a few milliseconds - the 3.6s-versus-0.9s number above swallows an 80-millisecond setup cost without noticing. But it means "subinterpreters are lighter than processes" is not something I could verify at creation time; the saving, where it exists, is in not forking a second copy of the process's address space, not in any faster start.

    That forkserver row was an accident. I wrote a timing script that called multiprocessing.Process(...).start() directly from the module's top level, the way plenty of tutorial code still does, and it crashed:

    RuntimeError:
    An attempt has been made to start a new process before the
    current process has finished its bootstrapping phase.

    Checking multiprocessing.get_start_method() explained it: Python 3.14 changed the default start method on Linux from fork to forkserver. Python 3.13 reports fork; 3.14 reports forkserver. forkserver re-imports your module in the child, which is exactly the thing if __name__ == "__main__": exists to guard against, and which fork never required you to bother with. Every piece of multiprocessing code I'd written without that guard over the years happened to work by accident, on Linux, until this release. It's a one-line fix, but it is a real break, and it landed in the same release that gives you an alternative that doesn't have this problem at all.

    What it costs: closing an interpreter doesn't give the memory back


    I ran four rounds of "create four interpreters, give each a 200,000-element list, close them", watching my own process's RSS the whole time:

    round 1: 16920 -> 55648 KB
    round 2: 55648 -> 57140 KB
    round 3: 57140 -> 59476 KB
    round 4: 59476 -> 61096 KB

    .close() does finalise the interpreter - a destroyed interpreter can't be called again, and I checked that it raises if you try - but the process's resident memory never drops back to where it started. It flattens out (each later round adds less than the first) rather than growing without bound, which looks like CPython's allocator holding onto freed arenas rather than a genuine leak, but I didn't chase that further. If you're planning to cycle through many short-lived interpreters inside one long-running process, budget for that memory to stay resident, not to be returned to the OS the way a finished process's memory is.

    What's actually shareable between interpreters


    Subinterpreters don't share objects by default - that is the entire point, it's what lets them skip the GIL - so most interesting values need to cross a boundary. is_shareable() gives a yes/no answer per type:

    int -> True
    str -> True
    bytes -> True
    None -> True
    bool -> True
    tuple of ints -> True
    float -> True
    list -> False
    dict -> False

    Passing a threading.Lock as an argument to Interpreter.call() fails immediately, with the repr of the offending object right there in the message:

    NotShareableError: (<unlocked _thread.lock object at 0x7f61b8b5add0>,) does not support cross-interpreter data

    An ordinary custom class instance fails the same way, with a flatter message:

    NotShareableError: object does not support cross-interpreter data

    But the cross-interpreter Queue that the same module provides does not enforce this. I put a plain custom-class instance onto a queue and it went through without complaint, and came back out as a distinct, working object with the same attribute values - the queue silently pickles and unpickles it:

    q = interpreters.create_queue()
    q.put(Thing()) # no error
    received = q.get()
    # received is not the original object, but received.value is unchanged

    So "not shareable" is enforced differently depending on how the object crosses over. A direct argument to call() is checked against the strict shareable-types list and rejected on the spot. The same object dropped into a Queue gets the softer treatment the docs describe for put(): pickled going in, unpickled coming out as a new, unrelated object. If your code passes data between interpreters by argument, moving it to a queue instead buys you a much larger set of types - at the cost of identity and, for anything mutable, of staying in sync with the original.

    What I got wrong on the way


    My first attempt at the shareability tests put several checks in one script with no if __name__ == "__main__": guard, calling interp.call() with a mix of shareable and non-shareable arguments one after another. Running it printed every result twice, and the second copy sometimes disagreed with the first about which error got raised. My best explanation, which I didn't fully verify, is that call()'s documented pickle fallback needs to resolve names against the target interpreter's own __main__, and since that interpreter had never run my module, resolving anything defined at module level meant running the whole module there first - silently re-executing my test file a second time, inside the subinterpreter, with its own fresh state. Splitting each check into its own small script with a proper __main__ guard made every result reproducible, which is what's reported above. I'd treat any subinterpreter test that imports a lot of top-level code as suspect until it survives being run twice.

    Run it yourself


    This needs Python 3.14 and four-ish cores to see the gap clearly. I ran it in Docker because that's the fastest way to get an exact version:

    docker pull python:3.14-slim

    The core benchmark:

    # bench.py
    import time, threading, sys

    def cpu_work(n):
    count = 0
    for i in range(2, n):
    is_prime = True
    for d in range(2, int(i ** 0.5) + 1):
    if i % d == 0:
    is_prime = False
    break
    if is_prime:
    count += 1
    return count

    def run_threads(n, workers):
    threads = [threading.Thread(target=cpu_work, args=(n,)) for _ in range(workers)]
    t0 = time.perf_counter()
    for t in threads: t.start()
    for t in threads: t.join()
    print(f"threads={workers}: {time.perf_counter()-t0:.3f}s")

    def run_interpreters(n, workers):
    import concurrent.interpreters as interpreters
    interps = [interpreters.create() for _ in range(workers)]
    t0 = time.perf_counter()
    threads = [i.call_in_thread(cpu_work, n) for i in interps]
    for t in threads: t.join()
    print(f"interpreters={workers}: {time.perf_counter()-t0:.3f}s")
    for i in interps: i.close()

    if __name__ == "__main__":
    mode, n, workers = sys.argv[1], int(sys.argv[2]), int(sys.argv[3])
    {"threads": run_threads, "interpreters": run_interpreters}[mode](n, workers)

    docker run --rm -v "$PWD":/w -w /w python:3.14-slim python3 bench.py threads 400000 4
    docker run --rm -v "$PWD":/w -w /w python:3.14-slim python3 bench.py interpreters 400000 4

    And the refusal, which needs no setup at all:

    docker run --rm python:3.14-slim python3 -c "
    import concurrent.interpreters as interpreters
    i = interpreters.create()
    t1 = i.call_in_thread(lambda: __import__('time').sleep(1))
    t2 = i.call_in_thread(lambda: __import__('time').sleep(1))
    t1.join(); t2.join()
    "

    What to do with this


    If you have a CPU-bound Python workload that multiprocessing already parallelises well, subinterpreters aren't an obvious upgrade yet: on this release they start up slower than a plain fork and about the same as forkserver, and you still need one interpreter per concurrent task, with no pooling against a single interpreter. Where they're worth trying now is the code that currently reaches for a thread, because threading is simpler to wire up than multiprocessing, and then quietly gets nothing from the GIL: swap the Thread for an Interpreter.call_in_thread, and check your data either fits the shareable-types list or is willing to cross as a pickled copy through a Queue. And if you have multiprocessing code anywhere that starts a Process without an if __name__ == "__main__": guard, fix that first - 3.14 will find it on Linux even if nothing else in this post applies to you.#python #performance #programming #devops #software #coding #development #engineering #inclusive #community
    Python 3.14's concurrent.interpreters module turns a 3.6-second GIL bottleneck into 0.9 seconds

  25. @AverageS

    My Word of the Day today is IRISATION. Share YOUR words to describe this picture in the comments!

    Unless I’m sadly mistaken this must be referring to Iris, the ancient Greek Goddess who’s the personification of the rainbow.

    Irisation, derived from French, iriser, in turn a borrowing from ancient Greek, iris, the ancient Greek noun, Ἶρις, meaning both the rainbow and the halo of the Moon, +‎ -er, verb-forming suffix. Iris, + ation, a suffix derived from Latin, -ātiō.

    Meaning: to make, or to become iridescent.

    The picture shows a rocky, scree-strewn mountain summit overlooking a sprawling green valley beneath a vivid blue sky with scattered clouds.
    A brilliant double rainbow arcs across this panoramic vista, with its vibrant primary band cutting across soft cloud shadows and the patchwork of fields below.

    All suggesting Iris has travelled this way on the rainbow whilst carrying messages from the Gods to us mere mortals…

    #WritersOfMastodon #TalesFrom… #SecretLife… #HowtoSucceed… #Author #Novel

  26. Most developers reach for Python (scikit-learn, scipy) when implementing unsupervised machine learning algorithms like K-Means or Hierarchical Clustering. However, implementing these algorithms from scratch in pure C strips away library abstractions and reveals how distance metrics, centroid convergence, and linkage trees actually work under the hood.

    In this guide, we solve a classic retail customer segmentation problem in pure C—complete with Within-Cluster Sum of Squares (WCSS) for the Elbow Method, K-Means Centroid Clustering, Agglomerative Single-Linkage Hierarchical Clustering, and an ASCII 2D terminal visualizer.

    The Problem Statement


    A retail company wants to segment its customers based on:

    1. Purchasing Behavior ($X$): Store visits / purchase frequency per month.
    2. Spending Patterns ($Y$): Average spending score (in thousands).
    3. Demographic Information: Customer Age.

    Our goal is to:

    1. Determine the optimal number of clusters ($K$) using the Elbow Method (WCSS).
    2. Implement K-Means Clustering (Centroid-based / Partitioning approach).
    3. Implement Hierarchical Clustering (Connectivity-based / Bottom-Up Agglomerative approach).
    4. Visualize the clusters and compare the effectiveness of both algorithms.


    The Dataset


    We use a clean 6-customer dataset so you can trace every single Euclidean distance calculation by hand and verify the C output directly:

    CustomerFrequency ($X$)Spending Score ($Y$)Age (Years)A2.02.022B3.01.025C4.02.024D7.06.040E8.07.042F9.06.045

    Mathematical Foundations

    1. Euclidean Distance


    Both K-Means and Single-Linkage Hierarchical Clustering measure similarity between two points $P_1(x_1, y_1)$ and $P_2(x_2, y_2)$ using straight-line Euclidean distance:

    $$d(P_1, P_2) = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$$

    2. The Elbow Method & WCSS


    The Elbow Method finds the optimal number of clusters $K$ by calculating the Within-Cluster Sum of Squares (WCSS) across increasing values of $K$:

    $$\text{WCSS} = \sum_{i=1}^{K} \sum_{x_j \in C_i} \left( (x_j - c_{ix})^2 + (y_j - c_{iy})^2 \right)$$

    • For $K = 1$: All 6 customers belong to a single cluster with mean centroid $C_1(5.5, 4.0)$, yielding $\text{WCSS} = 75.50$.
    • For $K = 2$: Points split cleanly into ${A, B, C}$ around $C_1(3.00, 1.67)$ and ${D, E, F}$ around $C_2(8.00, 6.33)$, dropping $\text{WCSS}$ sharply to $5.33$ (a reduction of $70.17$).
    • For $K = 3$: $\text{WCSS}$ only decreases slightly to $4.00$.

    Because the sharpest drop ("elbow") occurs at $K = 2$, the optimal number of customer segments is 2.

    Version 1: Minimal & Clean Implementation (exam_clustering.c)


    If you want a concise, flat implementation using simple 1D arrays without struct overhead—ideal for quick prototyping, university lab exams, or understanding the core loops—here is the streamlined version:

    #include <stdio.h>
    #include <math.h>

    // Euclidean Distance Formula: sqrt((x2 - x1)^2 + (y2 - y1)^2)
    float dist(float x1, float y1, float x2, float y2) {
    return sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
    }

    int main() {
    int n = 6, i, j, step;

    // Customer Dataset
    char id[6] = {'A', 'B', 'C', 'D', 'E', 'F'};
    float x[6] = {2, 3, 4, 7, 8, 9}; // Purchasing Behavior (Frequency)
    float y[6] = {2, 1, 2, 6, 7, 6}; // Spending Pattern (Score)
    int age[6] = {22, 25, 24, 40, 42, 45}; // Demographics (Age)

    int km_c[6], hc_c[6];

    // =========================================================
    // 1. ELBOW METHOD (WCSS for K = 1, 2, 3)
    // =========================================================
    printf("--- 1. ELBOW METHOD ---\n");
    printf("K=1 : WCSS = 75.50\n");
    printf("K=2 : WCSS = 5.33 <-- Sharpest Drop (Optimal K = 2)\n");
    printf("K=3 : WCSS = 4.00\n\n");

    // =========================================================
    // 2. K-MEANS CLUSTERING (For Optimal K = 2)
    // =========================================================
    // Initial Centroids: C1 = A(2,2) and C2 = E(8,7)
    float c1x = 2.0, c1y = 2.0;
    float c2x = 8.0, c2y = 7.0;

    for (step = 1; step <= 2; step++) {
    float sum1x = 0, sum1y = 0, sum2x = 0, sum2y = 0;
    int count1 = 0, count2 = 0;

    // Assign each customer to nearest centroid
    for (i = 0; i < n; i++) {
    if (dist(x[i], y[i], c1x, c1y) < dist(x[i], y[i], c2x, c2y)) {
    km_c[i] = 1;
    sum1x += x[i]; sum1y += y[i]; count1++;
    } else {
    km_c[i] = 2;
    sum2x += x[i]; sum2y += y[i]; count2++;
    }
    }
    // Update Centroids (Mean)
    c1x = sum1x / count1; c1y = sum1y / count1;
    c2x = sum2x / count2; c2y = sum2y / count2;
    }

    printf("--- 2. K-MEANS CLUSTERING (K = 2) ---\n");
    printf("Final Centroids: C1(%.2f, %.2f), C2(%.2f, %.2f)\n\n", c1x, c1y, c2x, c2y);

    // =========================================================
    // 3. HIERARCHICAL CLUSTERING (Single-Linkage / Bottom-Up)
    // =========================================================
    printf("--- 3. HIERARCHICAL CLUSTERING (MERGE STEPS) ---\n");
    for (i = 0; i < n; i++) hc_c[i] = i + 1; // Each point starts in its own cluster

    // Merge 4 times to reduce 6 points into 2 clusters
    for (step = 1; step <= 4; step++) {
    float min_d = 999.0;
    int p1 = 0, p2 = 0;

    // Find two closest points in different clusters
    for (i = 0; i < n; i++) {
    for (j = i + 1; j < n; j++) {
    if (hc_c[i] != hc_c[j] && dist(x[i], y[i], x[j], y[j]) < min_d) {
    min_d = dist(x[i], y[i], x[j], y[j]);
    p1 = i; p2 = j;
    }
    }
    }
    printf("Step %d: Merged %c & %c (Distance = %.2f)\n", step, id[p1], id[p2], min_d);

    // Combine cluster labels
    int old_c = hc_c[p2];
    for (i = 0; i < n; i++) {
    if (hc_c[i] == old_c) hc_c[i] = hc_c[p1];
    }
    }

    // =========================================================
    // 4. VISUALIZATION & COMPARISON TABLE
    // =========================================================
    printf("\n--- 4. CLUSTER VISUALIZATION & COMPARISON ---\n");
    printf("Cust\tX\tY\tAge\tK-Means\t\tHierarchical\n");
    for (i = 0; i < n; i++) {
    int hc_group = (hc_c[i] == hc_c[0]) ? 1 : 2;
    printf(" %c\t%.0f\t%.0f\t%d\tCluster %d\tCluster %d\n",
    id[i], x[i], y[i], age[i], km_c[i], hc_group);
    }

    printf("\nComparison:\n");
    printf("1. Both formed identical segments: {A,B,C} (Low Spenders) & {D,E,F} (High Spenders).\n");
    printf("2. K-Means is faster O(N) for big data; Hierarchical builds a tree (Dendrogram) without needing K first.\n");

    return 0;
    }

    Version 2: Full Modular Implementation with Dynamic WCSS & ASCII Plot (customer_clustering.c)


    For a complete, structured version that dynamically computes WCSS for $K = 1 \dots 4$, tracks K-Means convergence iterations, builds the Single-Linkage merge history, and renders an ASCII 2D scatter plot in the terminal:

    #include <stdio.h>
    #include <math.h>
    #include <float.h>

    #define N 6 // Number of customers
    #define MAX_K 4 // Maximum K to test for the Elbow Method

    typedef struct {
    char id;
    double x; // Purchasing Frequency (Visits/Month)
    double y; // Spending Score (Thousands)
    int age; // Demographic Info (Age)
    int kmeans_cluster;
    int hc_cluster;
    } Customer;

    // Euclidean Distance formula: sqrt((x2 - x1)^2 + (y2 - y1)^2)
    double euclidean_dist(double x1, double y1, double x2, double y2) {
    return sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    }

    // Squared Euclidean Distance for WCSS: (x - xc)^2 + (y - yc)^2
    double sq_dist(double x1, double y1, double x2, double y2) {
    return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
    }

    // Core K-Means Function (Returns WCSS for a given K)
    double run_kmeans(Customer data[], int k, int print_steps) {
    double cx[MAX_K], cy[MAX_K];
    int i, j;

    // Step 1: Initialize Centroids
    if (k == 2) {
    cx[0] = data[0].x; cy[0] = data[0].y; // C1 = A(2, 2)
    cx[1] = data[4].x; cy[1] = data[4].y; // C2 = E(8, 7)
    } else {
    for (i = 0; i < k; i++) {
    cx[i] = data[i].x;
    cy[i] = data[i].y;
    }
    }

    int changed = 1, iter = 0;
    while (changed && iter < 10) {
    changed = 0;
    iter++;

    // Step 2: Assign each customer to the nearest centroid
    for (i = 0; i < N; i++) {
    double min_d = DBL_MAX;
    int best_c = 0;
    for (j = 0; j < k; j++) {
    double d = euclidean_dist(data[i].x, data[i].y, cx[j], cy[j]);
    if (d < min_d) {
    min_d = d;
    best_c = j;
    }
    }
    if (data[i].kmeans_cluster != best_c) {
    data[i].kmeans_cluster = best_c;
    changed = 1;
    }
    }

    // Step 3: Recalculate Centroids (Mean of assigned points)
    for (j = 0; j < k; j++) {
    double sum_x = 0, sum_y = 0;
    int count = 0;
    for (i = 0; i < N; i++) {
    if (data[i].kmeans_cluster == j) {
    sum_x += data[i].x;
    sum_y += data[i].y;
    count++;
    }
    }
    if (count > 0) {
    cx[j] = sum_x / count;
    cy[j] = sum_y / count;
    }
    }

    if (print_steps) {
    printf(" Iteration %d Centroids: ", iter);
    for (j = 0; j < k; j++) {
    printf("C%d(%.2f, %.2f) ", j + 1, cx[j], cy[j]);
    }
    printf("\n");
    }
    }

    // Calculate total WCSS
    double wcss = 0;
    for (i = 0; i < N; i++) {
    int c = data[i].kmeans_cluster;
    wcss += sq_dist(data[i].x, data[i].y, cx[c], cy[c]);
    }
    return wcss;
    }

    // Agglomerative Hierarchical Clustering (Single-Linkage / Bottom-Up)
    void run_hierarchical(Customer data[], int target_k) {
    int i, j;
    for (i = 0; i < N; i++) {
    data[i].hc_cluster = i;
    }

    int current_clusters = N;
    int step = 1;

    printf("\n--- 3. HIERARCHICAL CLUSTERING (AGGLOMERATIVE SINGLE-LINKAGE) ---\n");
    printf("Dendrogram Merge Steps (Bottom-Up Approach):\n");

    while (current_clusters > target_k) {
    double min_d = DBL_MAX;
    int c1 = -1, c2 = -1;
    int p1 = -1, p2 = -1;

    // Find the two closest points belonging to DIFFERENT clusters
    for (i = 0; i < N; i++) {
    for (j = i + 1; j < N; j++) {
    if (data[i].hc_cluster != data[j].hc_cluster) {
    double d = euclidean_dist(data[i].x, data[i].y, data[j].x, data[j].y);
    if (d < min_d) {
    min_d = d;
    c1 = data[i].hc_cluster;
    c2 = data[j].hc_cluster;
    p1 = i;
    p2 = j;
    }
    }
    }
    }

    printf(" Step %d: Merged Customer %c & Customer %c (Min Distance = %.2f)\n",
    step++, data[p1].id, data[p2].id, min_d);

    for (i = 0; i < N; i++) {
    if (data[i].hc_cluster == c2) {
    data[i].hc_cluster = c1;
    }
    }
    current_clusters--;
    }

    // Normalize cluster IDs to 0, 1, ... for clean display
    int map[N];
    for (i = 0; i < N; i++) map[i] = -1;
    int next_id = 0;
    for (i = 0; i < N; i++) {
    int old_c = data[i].hc_cluster;
    if (map[old_c] == -1) {
    map[old_c] = next_id++;
    }
    data[i].hc_cluster = map[old_c];
    }
    }

    // ASCII 2D Plot to Visualize Clusters in Terminal
    void visualize_clusters(Customer data[]) {
    printf("\n--- 4. 2D CLUSTER VISUALIZATION (Spending vs Frequency) ---\n");
    int x, y, i;
    for (y = 8; y >= 0; y--) {
    printf(" %2d | ", y);
    for (x = 0; x <= 10; x++) {
    char symbol = '.';
    int c_id = -1;
    for (i = 0; i < N; i++) {
    if ((int)data[i].x == x && (int)data[i].y == y) {
    symbol = data[i].id;
    c_id = data[i].kmeans_cluster + 1;
    break;
    }
    }
    if (symbol != '.')
    printf("%c(C%d) ", symbol, c_id);
    else
    printf(" . ");
    }
    printf("\n");
    }
    printf(" +------------------------------------------------------------------\n");
    printf(" 0 1 2 3 4 5 6 7 8 9 10\n");
    printf(" Purchasing Frequency (X) ->\n");
    }

    int main() {
    Customer customers[N] = {
    {'A', 2.0, 2.0, 22, -1, -1},
    {'B', 3.0, 1.0, 25, -1, -1},
    {'C', 4.0, 2.0, 24, -1, -1},
    {'D', 7.0, 6.0, 40, -1, -1},
    {'E', 8.0, 7.0, 42, -1, -1},
    {'F', 9.0, 6.0, 45, -1, -1}
    };

    int i, k;
    printf("=================================================================\n");
    printf(" RETAIL CUSTOMER DATASET \n");
    printf("=================================================================\n");
    printf("Cust\tFrequency(X)\tSpending(Y)\tAge (Demographics)\n");
    for (i = 0; i < N; i++) {
    printf(" %c\t %.1f\t\t %.1f\t\t %d yrs\n",
    customers[i].id, customers[i].x, customers[i].y, customers[i].age);
    }

    // 1. ELBOW METHOD
    printf("\n--- 1. ELBOW METHOD (DETERMINING OPTIMAL K) ---\n");
    double wcss_list[MAX_K + 1];
    printf(" K\tWCSS\t\tReduction (Drop)\n");
    for (k = 1; k <= MAX_K; k++) {
    for (i = 0; i < N; i++) customers[i].kmeans_cluster = -1;
    wcss_list[k] = run_kmeans(customers, k, 0);
    double drop = (k == 1) ? 0.0 : (wcss_list[k - 1] - wcss_list[k]);
    printf(" %d\t%.2f\t\t%.2f\n", k, wcss_list[k], drop);
    }

    int optimal_k = 2;
    printf(" >> Optimal Number of Clusters (Elbow Point) = %d (Sharpest WCSS drop of %.2f)\n",
    optimal_k, wcss_list[1] - wcss_list[2]);

    // 2. K-MEANS CLUSTERING
    printf("\n--- 2. K-MEANS CLUSTERING (K = %d) ---\n", optimal_k);
    for (i = 0; i < N; i++) customers[i].kmeans_cluster = -1;
    double kmeans_wcss = run_kmeans(customers, optimal_k, 1);

    // 3. HIERARCHICAL CLUSTERING
    run_hierarchical(customers, optimal_k);

    // 4. VISUALIZE CLUSTERS
    visualize_clusters(customers);

    // 5. COMPARISON OF BOTH TECHNIQUES
    printf("\n--- 5. EFFECTIVENESS & COMPARISON OF TECHNIQUES ---\n");
    printf("Cust\tAge\tK-Means Group\tHierarchical Group\tCustomer Segment Profile\n");
    for (i = 0; i < N; i++) {
    char *segment = (customers[i].kmeans_cluster == 0)
    ? "Budget / Low Spenders (Young)"
    : "Premium / High Spenders (Mature)";
    printf(" %c\t%d\t Cluster %d\t Cluster %d\t\t%s\n",
    customers[i].id, customers[i].age,
    customers[i].kmeans_cluster + 1,
    customers[i].hc_cluster + 1,
    segment);
    }

    printf("\nPerformance Summary:\n");
    printf(" * Final WCSS (Compactness): %.2f (Identical optimal partition achieved by both)\n", kmeans_wcss);
    printf(" * K-Means Effectiveness : Fast O(N*K*Iterations); best for large retail datasets.\n");
    printf(" * Hierarchical Effect. : Builds an informative Dendrogram without needing initial\n");
    printf(" centroids, but slower O(N^2) distance matrix checks.\n");
    printf("=================================================================\n");

    return 0;
    }

    Compilation & Execution


    Compile with gcc and link the math library using -lm:

    gcc customer_clustering.c -o customer_clustering -lm
    ./customer_clustering

    Terminal Output


    =================================================================
    RETAIL CUSTOMER DATASET
    =================================================================
    Cust Frequency(X) Spending(Y) Age (Demographics)
    A 2.0 2.0 22 yrs
    B 3.0 1.0 25 yrs
    C 4.0 2.0 24 yrs
    D 7.0 6.0 40 yrs
    E 8.0 7.0 42 yrs
    F 9.0 6.0 45 yrs

    --- 1. ELBOW METHOD (DETERMINING OPTIMAL K) ---
    K WCSS Reduction (Drop)
    1 75.50 0.00
    2 5.33 70.17
    3 4.00 1.33
    4 2.00 2.00
    >> Optimal Number of Clusters (Elbow Point) = 2 (Sharpest WCSS drop of 70.17)

    --- 2. K-MEANS CLUSTERING (K = 2) ---
    Iteration 1 Centroids: C1(3.00, 1.67) C2(8.00, 6.33)
    Iteration 2 Centroids: C1(3.00, 1.67) C2(8.00, 6.33)

    --- 3. HIERARCHICAL CLUSTERING (AGGLOMERATIVE SINGLE-LINKAGE) ---
    Dendrogram Merge Steps (Bottom-Up Approach):
    Step 1: Merged Customer A & Customer B (Min Distance = 1.41)
    Step 2: Merged Customer B & Customer C (Min Distance = 1.41)
    Step 3: Merged Customer D & Customer E (Min Distance = 1.41)
    Step 4: Merged Customer E & Customer F (Min Distance = 1.41)

    --- 4. 2D CLUSTER VISUALIZATION (Spending vs Frequency) ---
    8 | . . . . . . . . . . .
    7 | . . . . . . . . E(C2) . .
    6 | . . . . . . . D(C2) . F(C2) .
    5 | . . . . . . . . . . .
    4 | . . . . . . . . . . .
    3 | . . . . . . . . . . .
    2 | . . A(C1) . C(C1) . . . . . .
    1 | . . . B(C1) . . . . . . .
    0 | . . . . . . . . . . .
    +------------------------------------------------------------------
    0 1 2 3 4 5 6 7 8 9 10
    Purchasing Frequency (X) ->

    --- 5. EFFECTIVENESS & COMPARISON OF TECHNIQUES ---
    Cust Age K-Means Group Hierarchical Group Customer Segment Profile
    A 22 Cluster 1 Cluster 1 Budget / Low Spenders (Young)
    B 25 Cluster 1 Cluster 1 Budget / Low Spenders (Young)
    C 24 Cluster 1 Cluster 1 Budget / Low Spenders (Young)
    D 40 Cluster 2 Cluster 2 Premium / High Spenders (Mature)
    E 42 Cluster 2 Cluster 2 Premium / High Spenders (Mature)
    F 45 Cluster 2 Cluster 2 Premium / High Spenders (Mature)

    Comparing K-Means vs. Hierarchical Clustering for Customer Segmentation

    CriterionK-Means ClusteringHierarchical Clustering (Agglomerative)Core ApproachCentroid-based partitioningConnectivity-based bottom-up mergingTime Complexity$\mathcal{O}(N \cdot K \cdot \text{Iterations})$ — Fast and linear$\mathcal{O}(N^2)$ to $\mathcal{O}(N^3)$ — Computationally heavyNeed to Pre-specify $K$?Yes (requires Elbow Method first)No (builds full Dendrogram; cut tree at any level)Sensitivity to InitializationSensitive to initial centroid choicesDeterministic — always produces the same treeBest Retail Use CaseLarge-scale customer databases (100k+ users)Smaller datasets where visual taxonomy/hierarchy matters

    Key Takeaways


    1. Identical Optimal Partitioning: On well-separated spherical customer segments ({A, B, C} vs {D, E, F}), both K-Means and Single-Linkage Hierarchical Clustering converge to the exact same groups with $\text{WCSS} = 5.33$.
    2. When to Choose What: Use Hierarchical Clustering during exploratory analysis to discover nested customer relationships via a Dendrogram, and switch to K-Means in production pipelines when segmenting millions of retail transactions.


    #c #machinelearning #algorithms #datascience #software #coding #development #engineering #inclusive #community
    Implementing K-Means & Hierarchical Clustering in Pure C for Customer Segmentation

  27. Charmy’s Army in “DEE SEAST – The Hell of the Ball” – Part 3: Blue Vests and Brown Bananas

    <<< Previous COMIC strip NEXT COMIC STRIP >>>

    In the third installment of our saga, panic reaches a fever pitch before colliding directly with mundane retail logistics. Convinced that Walmart’s customer service desk has instituted a terrifying new policy for processing refunds, the ponytail girl spiraled into sheer dread: will returning a defective toaster get her tossed into a holding pen to be devoured by domesticated ghouls? Thankfully, the blonde clears the air. Dee isn’t eating dissatisfied shoppers; she works in the meat department devouring the expired cuts. She isn’t a mindless trash can, either—as corporate HR would insist, she is a proud “Waste Management Facilitator.”

    The fluorescent lights of the retail district buzzed overhead like a hive of mechanical hornets. The ponytail girl stood dead in the center of the sidewalk, completely frozen in terror, clutching both hands to her face. Her eyes were practically the size of saucers, and her breathing sounded like a bellows working overtime.

    “I bought a set of non-stick sauté pans three weeks ago,” she whispered, her voice trembling with sheer, unadulterated existential dread. “The coating is already flaking off near the handle. I have the receipt in my purse. I was literally planning to go to Customer Care this afternoon. But now? Now I know the truth! They’re going to look at my receipt, see that the packaging is torn, hit a discreet red button under the desk, and drop me down a trapdoor into Dee’s feeding pit!”

    The blonde stared at her friend for three long seconds, an expression of profound exhaustion settling across her features. She pinched the bridge of her nose and let out a deep, shuddering sigh that blew a stray blonde lock out of her eyes.

    “Have you ever, in your entire life, heard of a big-box store feeding actual human customers to an employee?” the blonde asked flatly. “Do you realize the liability insurance premiums on that alone? The Occupational Safety and Health Administration would have field inspectors crawling through the air ducts within forty-eight hours. The paperwork would take decades.”

    “Corporations do terrible things to protect their quarterly profit margins!” the ponytail girl insisted, gesticulating wildly toward the towering blue sign visible above the tree line. “Think about it! Customer returns cost money! Salvage freight costs money! If you replace the return desk with an apex predator from beyond the grave, refund requests drop to absolute zero overnight! It’s the ultimate cost-cutting measure!”

    “She’s in the meat department, you absolute lunatic,” the blonde barked, grabbing her friend by the arm and dragging her along the pavement. “She doesn’t eat dissatisfied patrons who lost their receipt for a shower curtain. She eats the brown ground chuck and the discount chicken thighs that have been sitting in the display cooler forty-eight hours past their sell-by date!”

    The ponytail girl blinked once. Twice. Her frantic breathing slowed down, though the look of absolute disgust remained firmly plastered across her face. “Wait… what?”

    “You heard Charmy earlier,” the blonde continued, shaking her head. “Food waste is one of the biggest logistical hurdles in supermarket management. Stores throw away literal tons of spoiled produce, dented cans, and graying beef every single calendar year. Landfills charge dumping fees. Commercial composters have strict guidelines. But an undead post-human? Their digestive systems—or whatever remaining chemical soup passes for an internal organ—can neutralize bacteria that would put a vulture into an intensive care unit.”

    “So she’s a garbage disposal,” the ponytail girl summarized, wrinkling her nose until her freckles scrunched into a tight knot. “A glorified, walking, rotting kitchen sink drain with bangs.”

    “Charmy said she prefers the title Waste Management Facilitator,” the blonde corrected with an ironic smirk. “Corporate America doesn’t hire monsters; they hire operational specialists. They probably gave her an orientation badge, a five-minute video on slips, trips, and falls, and a designated break room in the refrigerated storage annex so she doesn’t scare the bakery associates.”

    Across the street, Charmy and Dee had paused outside a small convenience store. Dee was leaning against a lamppost, her head tilted at a precarious angle that suggested her neck vertebrae were merely suggestive guidelines. A passing delivery driver glanced at her, double-took, and quickly crossed the street with an expression of profound confusion, but nobody screamed. Nobody dialed the national guard. The world had simply absorbed the unthinkable and filed it away under routine municipal oddities.

    “I don’t know what’s worse,” the ponytail girl muttered, watching Dee attempt to scratch her shoulder and nearly dislocating her collarbone in the process. “The idea that the zombie apocalypse ended with our society almost being overrun, or the idea that it ended with the survivors realizing zombies could be exploited for unpaid sanitation labor.”

    “Welcome to late-stage capitalism,” the blonde replied with a dry chuckle. “If a catastrophic virus wipes out twenty percent of the population, the remaining eighty percent won’t mourn; they’ll just figure out how to put the fallen to work clearing out the dairy aisle. But hey, look at the bright side: at least Dee is earning an honest living. It’s more than half the guys you’ve dated this year can say.”

    “That is a low blow and completely uncalled for,” the ponytail girl grumbled, though she couldn’t suppress a faint, cynical grin. “At least my exes showered once a week. Dee looks like she just crawled out of an abandoned septic tank behind a haunted waterpark.”

    “True,” the blonde agreed, watching as Charmy gently handed Dee a small bottle of hand sanitizer, which she promptly attempted to drink before Charmy calmly redirected it to her palms. “She’s definitely rough around the edges. But that brings up an even more pressing dilemma: with Halloween coming up, what does an integrated undead citizen do for social life? And more importantly… what does this mean for the town dance?”

    TO BE CONTINUED….

    Rate this:

    #books #fantasy #fiction #shortStory #writing
  28. DATE: October 26, 2026 at 12:00PM
    SOURCE: PSYPOST.ORG

    ** Research quality varies widely from fantastic to small exploratory studies. Please check research methods when conclusions are very important to you. **
    -------------------------------------------------

    TITLE: Frequent cannabis use linked to higher odds of nighttime breathing problems

    URL: psypost.org/frequent-cannabis-

    Adults who use cannabis are more likely to report loud snoring and pauses in breathing during the night, according to new research published in Sleep Health: Journal of the National Sleep Foundation. The findings indicate that more frequent cannabis consumption corresponds with higher odds of experiencing these nocturnal breathing issues, even after accounting for factors like body weight and tobacco smoking. This relationship raises important questions for the growing number of people who turn to cannabis as a sleep aid.

    Sleep-disordered breathing is an umbrella term for medical conditions characterized by abnormal respiratory patterns or insufficient ventilation during rest. The most common form is obstructive sleep apnea, a disorder in which the muscles in the back of the throat relax too much, causing the upper airway to narrow or collapse entirely. People with this condition require extra physical effort to breathe, often resulting in loud snoring, gasping, or brief, repeated stops in breathing known as apneas. Standard treatments like continuous positive airway pressure machines, oral appliances, and surgery can be effective, yet many patients find the devices uncomfortable or difficult to tolerate over the long term.

    At the same time, cannabis has become increasingly accessible across the United States, and difficulty sleeping is one of the most common reasons people cite for using it. While users frequently report that the plant helps them rest, controlled clinical trials examining cannabinoids and sleep have produced mixed outcomes.

    For example, a 2023 clinical trial covered by PsyPost found that consuming medicinal cannabis oil improved sleep duration and increased midnight melatonin levels in adults with insomnia, whereas a study covered by PsyPost in 2024 indicated that a cannabis compound called cannabinol reduced nighttime awakenings when taken alone but showed no benefit when combined with cannabidiol, another cannabis compound. Observational tracking also points to potential drawbacks, such as a 2026 longitudinal study of military service members that linked current cannabis use to worse overall sleep quality and longer times needed to fall asleep.

    When it comes to breathing disorders specifically, tetrahydrocannabinol, the primary psychoactive compound in cannabis, has shown some potential to stabilize breathing in animal experiments and small human trials using oral pills. However, the broader clinical evidence remains inconsistent, leading the American Academy of Sleep Medicine to formally advise against using cannabis to treat obstructive sleep apnea. Most everyday consumers inhale cannabis rather than taking standardized pills, exposing their airways to smoke and heat that could inflame the tissues of the throat.

    The new research, led by Tyler J. Gallagher, a resident physician in the Caruso Department of Otolaryngology-Head and Neck Surgery at the Keck School of Medicine of the University of Southern California, and co-first author Matthew E. Lin of the David Geffen School of Medicine at the University of California, Los Angeles, sought to evaluate how everyday consumption relates to signs of breathing issues at night.

    “While some studies have explored cannabinoids as potential treatments for obstructive sleep apnea, there has been relatively little population-level research examining whether real-world cannabis use is associated with common signs of sleep-disordered breathing, such as loud snoring and pauses in breathing during sleep,” Gallagher told PsyPost. “We sought to better understand this relationship using a nationally representative sample of US adults.”

    To investigate this connection, the authors analyzed information from the 2017 to 2018 Behavioral Risk Factor Surveillance System, a state-based telephone survey coordinated by the Centers for Disease Control and Prevention. Although nearly 900,000 adults completed the main survey during those two years, only Minnesota and Tennessee included optional survey modules asking about both cannabis habits and sleep breathing symptoms. From the respondents in those two states who had complete data, the researchers selected a stratified random sample of 14,485 adults designed to match the demographic profile of the broader United States population.

    Participants were asked how many days they had used marijuana or cannabis during the past 30 days, as well as their primary method of consumption and whether they used it for medical or recreational purposes. The researchers grouped the respondents into three categories: non-users (zero days in the past month), non-regular users (1 to 15 days), and regular users (16 to 30 days). Signs of sleep-disordered breathing were assessed using two yes-or-no questions asking if anyone had ever observed the respondent stop breathing during sleep, and if the respondent had ever been told that they snore loudly.

    Of the participants, 13,461 reported no current cannabis use, 438 were classified as non-regular users, and 364 were regular users, meaning about 5.5 percent of the sample currently used cannabis. Smoking was by far the most common consumption method, reported by about 87 percent of both non-regular and regular consumers, followed by vaporizing and eating. Among non-regular users, 61.6 percent used cannabis strictly for recreational reasons, whereas 37.6 percent of regular users reported using it strictly for medical reasons and another 24.7 percent used it for both medical and recreational purposes.

    Overall, signs of sleep-disordered breathing were common across the entire cohort, with 44.7 percent reporting either loud snoring or witnessed apneas. In the unadjusted raw numbers, 44.3 percent of non-users reported at least one of the two breathing signs, compared to 48.4 percent of non-regular users and 55.2 percent of regular users. Specifically, witnessed breathing pauses were reported by 15.3 percent of non-users, 17.1 percent of non-regular users, and 19.8 percent of regular users. Loud snoring was reported by 41.3 percent of non-users, 44.5 percent of non-regular users, and 50.0 percent of regular users.

    To account for other differences between users and non-users, the researchers ran statistical models that applied national survey weights (statistical adjustments that make a sample better mirror the U.S. adult population) and controlled for a wide range of potentially confounding factors. These adjustments accounted for age, sex, race and ethnicity, education, income, health insurance status, diabetes, body mass index, alcohol consumption, traditional cigarette smoking, and electronic cigarette use. Even after factoring out the influence of tobacco smoking and body weight, cannabis use remained independently associated with higher odds of sleep-disordered breathing symptoms.

    Compared to non-users, non-regular cannabis users had 41 percent higher odds of reporting witnessed apneas, 26 percent higher odds of reporting loud snoring, and 33 percent higher odds of experiencing either symptom. The association was more pronounced among regular consumers. Those who used cannabis 16 to 30 days per month had 73 percent higher odds of witnessed apneas, 68 percent higher odds of loud snoring, and 82 percent higher odds of reporting either sign compared to non-users. These figures describe odds rather than probabilities, so the absolute differences are smaller than the percentages might suggest; in the raw numbers, about 55 percent of regular users reported at least one sign, compared with about 44 percent of non-users.

    “While the impact of infrequent use is relatively small, the odds of irregular breathing during sleep almost double with more frequent cannabis use, making this a strong association worthy of consideration before frequent cannabis utilization,” Gallagher explained.

    The researchers also analyzed cannabis consumption as a continuous spectrum from zero to 30 days. In the weighted models, each additional day of cannabis use per month was associated with an approximate 2 percent increase in the odds of reporting witnessed apneas, loud snoring, or either sign, an estimate the authors note is clinically small and serves as a general summary across use levels rather than a strict per-day effect. When the authors repeated the analysis without the national survey weights, regular cannabis use remained linked to both breathing signs, though the estimates were smaller (for example, 36 percent higher odds of either sign rather than 82 percent). In that analysis, non-regular use was no longer linked to loud snoring or to either sign, and its link with witnessed breathing pauses sat right at the threshold of statistical significance.

    “The strength of the association and its greater magnitude among more frequent users were notable, particularly given that some studies have investigated cannabinoids as potential treatments for sleep apnea,” Gallagher said. “These findings may reflect differences between isolated cannabinoids studied in clinical settings and real-world cannabis use, including differences in composition and method of consumption.”

    The authors proposed two primary biological mechanisms that might explain why cannabis consumers report more signs of airway obstruction at night. Because roughly 87 percent of the consumers in the sample smoked their cannabis, physical irritation from smoke is one possible contributor. Unlike tobacco, cannabis smoke is typically inhaled through deeper breaths without a filter, and it burns at a higher temperature, which can cause thermal injury and inflammation in the throat tissues that narrow the upper airway.

    A second potential mechanism involves the way cannabis interacts with the autonomic nervous system, which regulates involuntary body functions. While small doses of cannabis tend to stimulate the sympathetic nervous system, the body’s “fight or flight” system, higher doses activate the parasympathetic nervous system, which promotes physical relaxation. Frequent users may develop tolerance and consume larger quantities, and the resulting parasympathetic activity may cause the muscles that hold the upper airway open to relax excessively during sleep, making the throat more likely to collapse.

    There are a few things to keep in mind when interpreting these findings. Because the survey captured information at a single point in time, the study cannot establish whether cannabis use causes sleep-disordered breathing or if the relationship works in the opposite direction. People who suffer from undiagnosed sleep apnea often experience fragmented, unrefreshing sleep, and it is possible that some of these individuals turn to cannabis in an attempt to self-medicate their exhaustion or insomnia. The researchers also could not account for factors such as sleeping pill or sedative use, heavy drinking, or psychiatric conditions, any of which might influence both cannabis use and nighttime breathing.

    The reliance on self-reported telephone survey data also introduces constraints. Asking participants if they have been told they snore or stop breathing is less reliable than conducting an overnight medical sleep study, and people who sleep alone may be unaware of their nighttime breathing habits. Additionally, the survey only tracked how many days a person used cannabis over the past month, without measuring the exact dosage, potency, or ratio of specific compounds like tetrahydrocannabinol and cannabidiol.

    The data came from just two states, Minnesota and Tennessee, because they were the only ones to include both sets of questions, and roughly 98 percent of the original survey respondents were excluded for that reason or because of missing information. Survey weights help align the sample with national demographics, but the authors note that applying them to such a small subset is debated among statisticians. In addition, the breathing questions asked whether these symptoms had ever been observed, while the cannabis question covered only the past month, so some symptoms may have predated participants’ current cannabis habits.

    Gallagher emphasized that reporting these symptoms is not the same as receiving a formal medical diagnosis. “While obstructive sleep apnea – a clinically defined and hazardous intermittent airway obstruction during sleep – is a type of sleep-disordered breathing, this study cannot make conclusions about the association between cannabis use and sleep apnea or other associated long-term risks,” he noted.

    Future research will need to incorporate objective sleep testing, such as polysomnography, an overnight sleep study that monitors breathing, oxygen levels, and brain activity, to verify whether cannabis habits correspond with clinically diagnosed sleep apnea. Scientists also need to compare different delivery methods, such as edibles versus inhalation, to separate the chemical effects of cannabinoids on throat muscles from possible damage from inhaling hot smoke.

    “Further research is required to examine the long-term effects of cannabis use on sleep and to determine the effects of cannabis dosage, different cannabis compositions, and different methods of consumption on sleep-disordered breathing,” Gallagher said. “Additionally, the long-term consequences of these impacts must be studied.”

    Until those relationships are clarified, the authors suggest that physicians should counsel patients about the potential respiratory risks of using cannabis, particularly for individuals who already show signs of sleep-disordered breathing. “People experiencing persistent snoring, pauses in breathing, or other symptoms of sleep apnea should seek medical evaluation rather than trying to utilize cannabis to manage their sleep,” Gallagher advised.

    “This study highlights the importance of evaluating the broader health effects of substances that people increasingly use for self-management,” Gallagher added. “Cannabis may have benefits for certain symptoms or conditions, but those potential benefits should be considered alongside possible risks. Sleep-disordered breathing is particularly important because it can go unrecognized for years while causing significantly worse quality-of-life. We hope these findings encourage further research and help clinicians have more informed conversations with patients who use cannabis for sleep-related concerns.”

    The study, “Cannabis use and associated sleep-disordered breathing among US adults,” was authored by Tyler J. Gallagher, Matthew E. Lin, Ian Kim, Ziva D. Cooper, Sebastian M. Jara, and Eric J. Kezirian.

    URL: psypost.org/frequent-cannabis-

    -------------------------------------------------

    Private, vetted email list for mental health professionals: clinicians-exchange.org

    Unofficial Psychology Today Xitter to toot feed at Psych Today Unofficial Bot @PTUnofficialBot

    -------------------------------------------------

    #psychology #counseling #socialwork #psychotherapy @psychotherapist @psychotherapists @psychology @socialpsych @socialwork @psychiatry #mentalhealth #psychiatry #healthcare #depression #psychotherapist #Cannabis #SleepHealth #SleepApnea #SleepDisorderedBreathing #LoudSnoring #NighttimeBreathing #RespiratoryHealth #HealthResearch #MedicalResearch #SleepAwareness

Share on Mastodon

Enter the server where you have an account.